1

我有一个奇怪的错误,生产中的范围不能反映当前时间。

module TimeFilter
  # Provides scopes to filter results based on time.
  def self.included(base)
    base.extend(ClassMethods)
    base.class_eval do
      scope :today, where(end_time: Time.zone.now.midnight..Time.zone.now)
      scope :this_week, where(end_time: Time.zone.now.beginning_of_week..Time.zone.now)
      scope :this_month, where(end_time: Time.zone.now.beginning_of_month..Time.zone.now)
      scope :older_than_this_month, where("end_time < ?", Time.zone.now.beginning_of_month)
      scope :last_month, where(end_time: Time.zone.now.beginning_of_month..Time.zone.now.beginning_of_month - 1.month)
    end
  end
end

Time.zone.now 似乎与 rails 控制台中的时间相同。

如果我将范围从库中移到我的模型中,它可以正常工作。难道我做错了什么?

4

1 回答 1

1

是的,您的范围正在评估一次,在class_eval. 要更正此问题,请为您的范围使用 lambda,如下所示:

  scope :today, lambda {where(end_time: Time.zone.now.midnight..Time.zone.now)}
  scope :this_week, lambda {where(end_time: Time.zone.now.beginning_of_week..Time.zone.now)}
  scope :this_month, lambda {where(end_time: Time.zone.now.beginning_of_month..Time.zone.now)}
  scope :older_than_this_month, lambda {where("end_time < ?", Time.zone.now.beginning_of_month)}
  scope :last_month, lambda {where(end_time: Time.zone.now.beginning_of_month..Time.zone.now.beginning_of_month - 1.month)}

这将导致时间在调用实际范围时进行评估,而不是在调用 eval 时进行评估。

于 2013-03-14T21:02:51.350 回答