Question

For bar_id = 1 a cache gets formed on first access. but even if bar_id is changed to 2 later on the values of 1 is retained. How do I make it work across bar_id(s)

 @foo = Rails.cache.fetch("foo_by_id", expires_in: 10.minutes) do
    Foo.where(:search => params['search'], :bar_id => params['bar_id']).first
 end
Was it helpful?

Solution

Your cache key must include any dynamic data you want to separate your cache by. In your case the cache key must include bar_id. What I'd do is:

@foo = Rails.cache.fetch("foo_by_id:#{params['bar_id']}", expires_in: 10.minutes) do
    Foo.where(:search => params['search'], :bar_id => params['bar_id']).first
 end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top