Model Scopes它可以将常用的查询条件放在Model中,方便在Controller中重用,让程式变得干净易读,更厉害的是可以串接使用。


scope实例:

class WebSite < ActiveRecord::Base
  scope :valid, where(:status => 1)
  scope :for_snatch, valid.cts.order("id")
end


scope传参数实例:

class Event < ActiveRecord::Base
  scope :recent, lambda{ |date| where(["created_at > ? ", date ]) }
  #或scope :recent, Proc.new{ |t| where(["created_at > ? ", t ]) }
end
Event.recent( Time.now - 7.days )


推荐上述这种带有参数的Scope ,改成如下的类别方法,可以比较明确看清楚参数是什么,特别是你想给预设值的时候

class Event < ActiveRecord::Base
  def self.recent(t=Time.now)
    where(["created_at > ? ", t ])
  end
end
Event.recent( Time.now - 7.days )




参考自:http://ihower.tw/rails3/activerecord.html