Do Not Forget: NamedScope and dates September 29th, 2008
One of the scopes I had in a project was from_this_month
class Transaction named_scope :from_this_month, :conditions => {:created_at => Time.now.beginning_of_month..Time.now} ... end
Which worked great to know all transactions from a user in a certain month. I could do current_user.transactions.from_this_month. When I tested this in developer mode all went well.. Production, however, didn’t work at all.
As we all know, Developer mode reloads classes every time you make a request. Production mode obviously doesn’t, so in Production, the first time you load the page you get a correct time-scope, if you do it a day later, however, the scope is still the same of yesterday. This can be solved with a proc or a lambda, which will get called on each request!
So, just to make sure I never forget, Use a lambda!
class Transaction named_scope :from_this_month, lambda { {:conditions => {:created_at => Time.now.beginning_of_month..Time.now}} } ... end
cool! i had been wondering what lambda was for a while..
Thanks for sharing!