天数范围从上次部署日期开始工作
Scope with days period works from the last deploy date
我有一个预订模型的范围,它将预订纳入当前的 15 天期间。它有效,因此,在生产中,一天后我发现它不起作用,从部署完成的那一刻起,在日志上应用范围过滤器。
首先,作用域如下所示:
scope :current_availables, where(date: Date.today..Date.today+14.days )
现在范围看起来像这样
scope :current_availables, where(date: Date.current.beginning_of_day..Date.current+14.days )
发生了什么事?
这来自 Rails 3.1.0 文档:
Note that scopes defined with scope will be evaluated when they are defined, rather than when they are used. For example, the following would be incorrect:
class Post < ActiveRecord::Base
scope :recent, where('published_at >= ?', Time.now - 1.week)
end
The example above would be ‘frozen’ to the Time.now value when the Post class was defined, and so the resultant SQL query would always be the same. The correct way to do this would be via a lambda, which will re-evaluate the scope each time it is called:
class Post < ActiveRecord::Base
scope :recent, lambda { where('published_at >= ?', Time.now - 1.week) }
end
因此,您可以尝试更新范围以使用 lambda 作为第二个参数,而不仅仅是 where
:
scope :current_availables, -> { where(date: Date.current.beginning_of_day..Date.current+14.days) }
(不确定是否可以使用 ->
如果不能使用 lambda
)
您也可以使用 14.days.from_now
而不是将 14 天添加到 Date.current
。
我有一个预订模型的范围,它将预订纳入当前的 15 天期间。它有效,因此,在生产中,一天后我发现它不起作用,从部署完成的那一刻起,在日志上应用范围过滤器。
首先,作用域如下所示:
scope :current_availables, where(date: Date.today..Date.today+14.days )
现在范围看起来像这样
scope :current_availables, where(date: Date.current.beginning_of_day..Date.current+14.days )
发生了什么事?
这来自 Rails 3.1.0 文档:
Note that scopes defined with scope will be evaluated when they are defined, rather than when they are used. For example, the following would be incorrect:
class Post < ActiveRecord::Base
scope :recent, where('published_at >= ?', Time.now - 1.week)
end
The example above would be ‘frozen’ to the Time.now value when the Post class was defined, and so the resultant SQL query would always be the same. The correct way to do this would be via a lambda, which will re-evaluate the scope each time it is called:
class Post < ActiveRecord::Base
scope :recent, lambda { where('published_at >= ?', Time.now - 1.week) }
end
因此,您可以尝试更新范围以使用 lambda 作为第二个参数,而不仅仅是 where
:
scope :current_availables, -> { where(date: Date.current.beginning_of_day..Date.current+14.days) }
(不确定是否可以使用 ->
如果不能使用 lambda
)
您也可以使用 14.days.from_now
而不是将 14 天添加到 Date.current
。