有人知道在Rails 3.1中查找本月创建记录的最佳查询吗?
有人知道在Rails 3.1中查找本月创建记录的最佳查询吗?
class Model
scope :this_month, -> { where(created_at: Time.now.beginning_of_month..Time.now.end_of_month) }
end
你可以这样调用它:
Model.this_month
initialize
- kidcapitalBETWEEN
:"created_at BETWEEN ? AND ?"
- Alex Peattie我更喜欢不用SQL:
Model.where(:created_at => Time.now.beginning_of_month..Time.now.end_of_month)
或者作为一个范围:
class Model < ActiveRecord::Base
scope :this_month, -> { where(:created_at => Time.now.beginning_of_month..Time.now.end_of_month) }
end
Time.now.beginning_of_month
将始终是最初评估作用域时该月份的开始。在作用域中使用日期的正确方法是将lambda传递给scope
。class Model < ActiveRecord::Base
scope :this_month, -> { where(created_at: Time.now.beginning_of_month..Time.now.end_of_month) }
end
Lambda
或Proc
。User.where('created_at >= ? and created_at <= ?', Time.now.beginning_of_month, Time.now.end_of_month)