Reputation: 23
Looks like Heroku cache scope result, and my questions is how they decide when to cache, when to refresh the scope result and how to use scope correctly. In my code, I have a name scope for the Question model like following
class Question < ActiveRecord::Base
scope :today, where('show_date = ?', Time.now.localtime("-07:00").strftime("%Y-%m-%d"))
end
And it always starts to give me the same cached result. My Guess is if I change Question Data, the Result will probably get updated. A quick research give me a related topic: Cached named_scope on Heroku?.
I already changed the code to be:
class Question < ActiveRecord::Base
def self.today
today_string = Time.now.localtime("-07:00").strftime("%Y-%m-%d");
where('show_date=?', today_string)
end
end
I guess this will always give me the correct result without any cache. But I an still wondering is there a better way to benefit from scope cache while get the correct result at the same time? Thanks.
Upvotes: 1
Views: 138
Reputation: 15736
Scopes are set when the application is first loaded so in the first case your scope query will be fixed to date at that time, until the application is restarted for whatever reason. It is the query definition rather than the query results that are getting cached here. Generally if you have a condition in your scope that is time dependent then your need to use a lambda to wrap the query definition within your scope, e.g.:
class Question < ActiveRecord::Base
scope :today, lambda { where('show_date = ?', Time.now.localtime("-07:00").strftime("%Y-%m-%d")) }
end
That will cache the scope definition but will execute the body of the lambda every time it is called. It will not cache the results of the query.
Upvotes: 3