named_scope - start using it!

Posted by Jason King about 1 year ago

As I pointed out here on the WWR Forums when you have a set of static conditions, even if you only use them once, then you should consider using a named_scope to encapsulate those conditions in your model.

So instead of having this in your controller:

app/controller/foos_controller.rb

def inactive
  @foos = Foo.all(:conditions => "active is null")
end

You would shift that concept off into your model by using a named scope. So you’d have this instead:

app/models/foo.rb

named_scope :inactive, :conditions => "active is null"

app/controller/foos_controller.rb

def inactive
  @foos = Foo.inactive
end

Note that what’s returned from inactive is a proper ActiveRecord collection, so you can call all your AR records on it, eg:

@foos = Foo.inactive.find_all_by_bar(params[:bar])

This is a great way to push the business logic off into your model and refer to it by name (not code) from your controller.