日期和范围不一致

时间:2012-06-01 12:18:50

标签: ruby-on-rails ruby-on-rails-3 datetime activerecord scope

我有以下范围:

scope :this_month, :conditions => ["created_at >= ?", Date.today.beginning_of_month]

这导致a.response_sets.this_month.to_sql的SQL输出:

SELECT "response_sets".* FROM "response_sets" WHERE created_at >= '2012-05-01'

但由于今天实际上是6月1日,那个日期似乎错了。所以,我试图绕过范围,直接做一个条件,如下:

a.response_sets.where(["created_at >= ?", Date.today.beginning_of_month]).to_sql

然后,输出:

SELECT "response_sets".* FROM "response_sets" WHERE created_at >= '2012-06-01'

哪个是对的。那么,为什么在范围内执行Date.today.beginning_of_month和直接在where中执行此操作会有区别?

1 个答案:

答案 0 :(得分:5)

在范围中使用日期时,您应该使用lambda,以便每次调用范围时对范围进行评估:

scope :this_month, -> { where("created_at >= ?", Date.today.beginning_of_month) }