Search code examples
ruby-on-railscachingdefaultscoping

Rails: default scoping being cached by query cache?


I got a default scoping like this which is dynamic:

default_scope :conditions => ["departure_date >= ?", DateTime.current.beginning_of_day]

When I use this code the first day is ok. Lets say first day is 28-03-2011

But the next day seems like it's still using "departure_date >= 28-03-2011"

Is my default scoping being cached?


Solution

  • The problem is that that code is only being executed once, when your app is loaded, and thus the actual date isn't changing. You need to change it to load lazily:

    default_scope lambda { { :conditions => ["departure_date >= ?", DateTime.current.beginning_of_day] } }
    

    This way, Datetime.current.beginning_of_day will be evaluated each time you make a query.