Rails的3.1 named_scope [英] Rails 3.1 named_scope
问题描述
什么是写低于code的Rails的3.1:
named_scope:min_2_items_last_90_days,{
:包括=> {:订单=> :ORDER_ITEMS},
:条件=> ['orders.created_at> =',90.days.ago]
:组=> people.id,
:有=> 'COUNT(order_items.id)> = 2'
}
在写为
范围:min_2_items_last_90_days,其中(...)
在语法上是正确的,它可能(像你原来的code)没有做完全是你的想法。
在这两种情况下的 90.days.ago
被计算一次只,上课的时候被加载,所以90日内将永远是前90天,你的应用程序的最后重新启动。如果您还没有重新启动10天你的应用程序,你会实际上是看在过去100天内创造的东西。在发展中,你不会注意到这一点,因为你的源$ C $ C不断被重新加载(因而 90.days
将重新评估)。
相反,你应该做的。
范围:min_2_items_last_90_days,拉姆达{其中('?orders.created_at> =',90.days.ago).includes(...)...}
这保证了条件将被重新评估每一个使用范围的时间。
What is the Rails 3.1 of writing the code below:
named_scope :min_2_items_last_90_days, {
:include => { :orders => :order_items },
:conditions => ['orders.created_at >= ?', 90.days.ago],
:group => 'people.id',
:having => 'COUNT(order_items.id) >= 2'
}
While writing it as
scope :min_2_items_last_90_days, where(...)
is syntactically correct, it probably (like your original code) doesn't do quite what you think.
In both cases the 90.days.ago
is evaluated once only, when the class is loaded, so the 90 days will always be 90 days before you app was last restarted. If you haven't restart your app for 10 days you'd actually be looking at stuff created in the last 100 days. You won't notice this in development because your source code is continuously being reloaded (and thus the 90.days
is reevaluated).
Instead you should do
scope :min_2_items_last_90_days, lambda { where('orders.created_at >= ?', 90.days.ago).includes(...) ... }
which ensures that the conditions will be re-evaluated every time you use the scope.
这篇关于Rails的3.1 named_scope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!