Rails 3.1 named_scope

What is Rails 3.1 for writing 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' } 
+4
source share
2 answers

When writing it like

 scope :min_2_items_last_90_days, where(...) 

is syntactically correct, it probably (like your source code) is not doing what you think.

In both cases, the parameter 90.days.ago is evaluated only once when the class is loaded, so 90 days will always be 90 days before the last restart of the application. If you do not restart the application within 10 days, you will actually look for things created in the last 100 days. You will not notice this in development because your source code is constantly reloading (and therefore revaluing 90.days ).

Instead you should do

 scope :min_2_items_last_90_days, lambda { where('orders.created_at >= ?', 90.days.ago).includes(...) ... } 

which ensures that conditions are re-evaluated each time you use the area.

+7
source
 scope :min_2_items_last_90_days, lambda { where('orders.created_at >= ?', 90.days.ago).includes(:orders => :order_items).group('people.id').having('COUNT(order_items.id) >= 2') } 

NB (because it's easy to forget) . Using a lambda ensures that conditions are reevaluated every time a scope is invoked (see also docs on scope ). And revaluation is necessary here because of the expression 90.days.ago - which you finally want to evaluate 90.days.ago every time an area is called . Without lambda, re-evaluation will not occur, and the expression 90.days.ago will be evaluated (only) when the server starts.

+2
source

Source: https://habr.com/ru/post/1388043/


All Articles