Rails Rails Model 的 scope 陷阱

chucai · 2012年09月03日 · 最后由 jjym 回复于 2012年09月03日 · 3816 次阅读

在 production 环境下,Model 的 scope 居然会有缓存 我的实际代码如下:

class Report < ActiveRecord::Base
  scope :recent_month, where("`reports`.`created_at` > ? AND `reports`.`created_at` < ?",  Time.now.at_beginning_of_mo    nth, Time.now.at_end_of_month)
...
end

我在上个月(8 月份)启动程序,在 9 月份的时候,日志居然显示

SELECT `reports`.* FROM `reports` WHERE (`reports`.`created_at` > '2012-08-01 00:00:00' AND `reports`.`created_at` < '2012-08-31 23:59:59'))

有遇到过这个问题的同学么?

此处有同样的问题: https://rails.lighthouseapp.com/projects/8994/tickets/4960-scopes-cached-in-production-mode

我的环境是 Ruby 1.9.2 Rails 3.2.3

你这个是直接传的值,当然是固定的。。可以传 lambda 或 proc。rails guides 上有

如果场景是这样就很容易理解为什么会出现上面这样的效果 class Report < ActiveRecord::Base scope :recent_month, where("reports.category_id = ?", 3) end

动态改为参数调用比较合适,不管是 scope 还是方法~

#1 楼 @jjym 恩,是不是 用 lambda 包装一层就可以了?

scope :recent_month, ->(){where("`reports`.`created_at` > ? AND `reports`.`created_at` < ?",  Time.now.at_beginning_of_mo    nth, Time.now.at_end_of_month)}
需要 登录 后方可回复, 如果你还没有账号请 注册新账号