Default Scoping

 

class Article < ActiveRecord::Base
  default_scope :order => 'created_at DESC'
end

 

现在,任何一个find或者named_scope方法执行,结果列表都会按照created_at DESC进行排序。

 

 

Article.find(:all) #=> "SELECT * FROM `articles` ORDER BY created_at DESC"

 

 

class Article < ActiveRecord::Base
  default_scope :order => 'created_at DESC'
  named_scope :published, :conditions => { :published => true }
end

Article.published #=> "SELECT * FROM `articles` WHERE published = true ORDER BY created_at DESC"

 

 

class Article < ActiveRecord::Base
  default_scope :order => 'created_at DESC'
  named_scope :published, :conditions => { :published => true },
                          :order => 'published_at DESC'
end

# published_at DESC clobbers default scope
Article.published
    #=> "SELECT * FROM `articles` WHERE published = true ORDER BY published_at DESC"

 

 

class Article < ActiveRecord::Base
  default_scope :order => 'created_at DESC'
end

# Ignore other scoping within this block
Article.with_exclusive_scope { find(:all) }  #=> "SELECT * FROM `articles`
 

 

你可能感兴趣的:(ActiveRecord)