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.

Hierarchy: previous, next

Comments

There are 2 comments on this post. Post yours →

Jared Haworth 1 day later

One of the best uses I’ve come across for named_scope is in dealing with associations:

For example, if you want to find all a user’s inactive foos, you could do:

@foos = @user.foos.inactive

(assuming you had defined that a user class has_many :foos).

The named scope is available anywhere you use the association.

Jason King 1 day later

Thanks for that Jared, that really does show the power of this feature.

Post a comment

Required fields look like this.

Markdown enabled. See the syntax rules for help.