UPDATE (7/29/2010) – If using Rails 3, then use “scope” instead of named scope.  Check out the Rails 3 query API also.

One of the cool new features in Ruby on Rails is the named_scope.  You can put a named_scope in your model as a way to do a customized find by just calling a name.  Here is an example of a simple named_scope.  This named scope gets all the widgets that are blue.  You can call it like this: Widget.blues

class Widget < ActiveRecord::Base
  named_scope :blues, :conditions=> "color='blue'"
end

Thats pretty cool huh? Very DRY if you are going to be using this quite a bit. Here is a more complex example where you can insert a parameter using lambda.

  named_scope :above_price, lambda { |*args| {:conditions => ["price>?",args.first] } }

  #get all widgets with price above $25
  Widget.above_price(25)

Even cooler…
Now here is something I like even better that I was not expecting, but it seems to work. I am able to chain these together to filter out different widgets based on criteria. This is useful in an application that needs to allow users to filter out certain content based on criteria. Lets say you have a list full of widgets of all kinds, but the user only wants to see widgets that are blue and cost more than $25. You can add some check boxes and inputs to your view with a submit button and let the user choose different criteria so they can find the widget they are looking for. Then you can filter out the widgets with named scopes in your controller

widgets = Widget.all
if params[:is_blue]
  widgets = widgets.blues
end
if params[:above_price]
  widgets = widgets.above_price(params[:above_price])
end
#now you would have all the blue widgets above whatever price the user entered in the field "above_price"

#If I remember correctly, you can also call them by chaining them together if you need to
widgets = widgets.blue.above_price(25)

I think this is a pretty elegant solution for doing object filtering in Rails. Go named_scope! You crazy!