scope的用法

scope可以将查询条件整合起来,让程序简洁易懂。并且可以串接使用。

1
2
3
4
5
6
7
8
class Event < ActiveRecord::Base
scope :open_public, -> { where( :is_public => true ) }
scope :recent_three_days, -> { where(["created_at > ? ", Time.now - 3.days ]) }
end
调用
Event.open_public
Event.open_public.recent_three_days

预设的scope

1
2
3
class Event < ActiveRecord::Base
default_scope -> { order('id DESC') }
end

暂时取消预设的scope

1
2
3
4
Event.unscoped do
Event.all
# SELECT * FROM events
end

1
2
3
4
5
6
7
8
class Event < ActiveRecord::Base
scope :recent, ->(date) { where("created_at > ?", date) }
# 等同於 scope :recent, lambda{ |date| where(["created_at > ? ", date ]) }
# 或 scope :recent, Proc.new{ |t| where(["created_at > ? ", t ]) }
end
Event.recent( Time.now - 7.days )