Reputation: 987
I am using rails cache in my application for caching Active Record queries. I used a common method for Rails.cache.fetch
, but it doesn't fetch the key. Am I missing anything here?
author = cache_fetch("author_id:#{current_user.id}") do
Author.find(current_user.id)
end
In my lib file:
cache_fetch(key)
Rails.cache.fetch(key,expires_in: 30.minutes)
end
Upvotes: 0
Views: 1205
Reputation: 62668
#fetch
takes a block, which is executed and the return value of which is cached if the key was not found in the cache. You should be using:
cache_fetch(key, options = {}, &block)
Rails.cache.fetch(key, options.reverse_merge(expires_in: 30.minutes), &block)
end
If you don't pass the block, then Rails won't know what to cache in the event of a miss, and thus won't have anything to return. The addition of the optional options
key allows you to pass overrides to cache_fetch
that will then get passed onto #fetch
, while still providing for defaults.
Upvotes: 3