September 2009


Chaining named_scope in Rails

David Carney, 18 September 2009

This is neat. In a model, you can have something like this:

class Foo < ActiveRecord::Base
named_scope :default, {:order => "priority DESC, last_modified DESC "}
named_scope :offset, lambda{|offset| {:offset => offset}}
named_scope :limit, lambda{|limit| {:limit => limit}}
...

Then, in a controller:

class FooController < ActionController::Base
def recent
offset = params[:offset] || 0
limit = params[:limit] || 100

foos = Foo.default.offset(offset).limit(limit)

The last line chains all of the parameters together, which builds a compound query. Moreover, you can define (and chain) much more complex named_scopes!

Very cool.