【问题标题】:Dates and scopes are inconsistent日期和范围不一致
【发布时间】:2012-06-01 12:18:49
【问题描述】:

我的范围如下:

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 中执行有区别呢?

【问题讨论】:

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


    【解决方案1】:

    在作用域中处理日期时,您应该使用 lambda,以便每次调用作用域时都会对其进行评估:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多