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.
Resources
- ActiveRecord API
- HABTM: Nested with_scope (great, detailed discussion)
- RubyInside code snippet
tags: rails, rubyonrails

with_scope is high_level access to an options merger, I’ve discovered.
I’ve been using association proxy extensions a lot lately, and other custom find methods. Here is a common idiom I’ll start with:
So you have a Employee object and has_many :phone_numbers
def find_by_phone_number(digits, params={}) self.with_scope(:find => params) do find(:first, :include => :phone_numbers, :conditions => ['phone_numbers.digits = ?', digits]) end endSo now you could say something like this:
employee.find_by_phone_number('2135552323', :conditions => ['phone_numbers.created_at > ?', Time.now - 2.weeks])I was wondering, if there is a reason that nested scopings overwrite all previous parameters by inner rule except :conditions in :find?
I also want to merge :joins. Therefore I tried to edit the base.rb of Active Record and added following to the with_scope method:
if key :conditions && merge ... elsif key :include && merge ... elsif key == :joins && merge #
—-added myself--hashmethod = merge_includes(hashmethod, params[key]).uniqThis works. Have anybody an idea why this isn’t in the rails core?
Soeren, I hope to see it in rails core.