Monday, January 10, 2011

Overide default scope in Rails


# Our default scope in question
class Product < ActiveRecord::Base
  default_scope order('created_at desc')
end

# This won't work
Product.order('created_at asc').all

# Method 1: unscoping
Product.unscoped.order('created_at asc').all

# Method 2: with_exclusive_scope
Product.with_exclusive_scope{ Product.order('created_at asc').all }

references: http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping