v3.0.9 - Show latest stable - 4 notes - Class: ActiveRecord::Base
default_scope(options = {}) protected

Sets the default options for the model. The format of the options argument is the same as in find.

class Person < ActiveRecord::Base
  default_scope order('last_name, first_name')

default_scope is also applied while creating/building a record. It is not applied while updating a record.

class Article < ActiveRecord::Base
  default_scope where(:published => true)

Article.new.published    # => true
Article.create.published # => true
Show source
Register or log in to add new notes.
June 4, 2011 - (>= v3.0.0)
4 thanks

finding without default scopes in rails 3

if you want to find without default scopes in rails 3 and with_exclusive_scope is giving you protected method errors in controllers, use unscoped for a similar purpose

February 26, 2010
3 thanks

default_scope on create

If you specify :conditions in your default_scope in form of a Hash, they will also be applied as default values for newly created objects. Example:

class Article
  default_scope :conditions => {:published => true}

Article.new.published? # => true


class Article
  default_scope :conditions => 'published = 1'

Article.new.published? # => false
March 26, 2012 - (<= v3.1.0)
1 thank

Use exist scopes on default_scope - pay attention

To use exists scopes on default_scope , you can use something like:

class Article < ActiveRecord::Base
  scope :active, proc {
    where("expires_at IS NULL or expires_at > '#{Time.now}'")

  scope :by_newest, order("created_at DESC")

  default_scope by_newest

But, if you would add a filter, and it require a lazy evaluate, use block on default_scope declaration, like:

default_scope { active.by_newest }