Rails 3 ActiveRecord scope and chainability Helpers

March 7th, 2011

The upgrade of Rails 2 to Rails 3 is a bunch of really helpful simplifications, including this one by changing named_scope to scope. Funny, it almost reminds me of how plain and simple the module names are for Drupal - Views, Backup & Restore, etc.

While simplifying it, Rails 3 adds to the scope concept by incorporating "chainability". I would normally refer to this concept as method chaining, but in this case of helpers, I gotta stick with chainability.

In short, scopes can now be chained together!

Here's a quick example:

class Memory < ActiveRecord::Base
  validates_presence_of :date
  scope :publik, :conditions => 'privacy = 10'

Class instantiation then looks something like this:

res = Memory.publik.where(:user_id =>
Yearly Indexes: 2003 2004 2006 2007 2008 2009 2010 2011 2012 2013 2015 2019 2020 2022