Pages

Tuesday, January 25, 2011

A Rails Feature You Should be Using: with_scope

A Rails Feature You Should be Using: with_scope
Posted by ryan at 5:48 AM on Thursday, July 20, 2006
The with_scope method provided by ActiveRecord has been talked about before (see the resources section below), but I don’t feel like people recognize what a great utility it is. Maybe awareness will increase with more tools that make use of this feature, like the MeantimeFilter by Roman, or just more public conversation about it. Add the following to the latter category:

with_scope lets you bind a block of code operating on an active record model to a particular subset of that model’s collection. For instance, using the standard blog application example, if I have a controller method that performs a series of operations on a single user’s articles I would need to pass in the user id condition on every operation:


def create_avoid_dups

user_id = current_user.id
# Find all user's posts
user_posts = Post.find(:all, :conditions => ["user_id = ?", user_id])

# Do some logic looking for dups in user_posts
...

# then create new
@post = Post.create(:body => params[:body], :user_id => user_id)

end

Notice we had to pass in the user_id on both the find and create method. with_scope lets us extract that parameter so the core operations aren’t obscured by excessive parameters:


def create_avoid_dups

Post.with_scope(:find => {:conditions => "user_id = #{current_user.id}"},
:create => {:user_id => current_user.id}) do

# Find all user's posts
# No longer need user_id condition since we're in scope
user_posts = Post.find(:all)

# Do some logic looking for dups in user_posts
...

# then create new without specifying user_id
@post = Post.create(:body => params[:body])
@post.user_id #=> user_id

end
end

with_scope allowed us to specify conditions of the Post that would apply throughout the course of the block (conditions specified by operation, in this case :find and :create)

Contrived examples such as this one don’t do a great job of showcasing how useful this method is – but imagine never having to specify the user_id in any controller method because it’s been automatically scoped to that user for you. That’s exactly what the previously mentioned meantime filter does.

So don’t be shy. If you find yourself writing code that applies to a known subset of items, scope it with with_scope. All the cool kids are doing it.

No comments:

Post a Comment