So right now users have a list of items that changes, but not too often, so I decided to keep it in a cache like so:
#Fetch the cache
def self.fetch_cache(user)
Rails.cache.fetch(user.items, :expires_in => 15.minutes) do
user.items.order("created_at ASC").all
end
end
This works if the user has items. The problem is, if the user doesn’t have any items (because they’re a new user or something) and the cache will return an error.
How should I be using this to make it work for users with nothing?
Thanks!
You’re using a really weird cache key there (the first argument to
Rails.cache.fetch). You’re supposed to be passing a string that identifies the cache entry but you’re passing in an association.Rails is probably helpfully calling
to_sonuser.itemsin order to turn it into a string that but that’s not a useful cache key as you’re going to have to load the user’s items in order to compute the cache key to get the users’ items from the cache!Something like
"user_#{user.id}_items"would be a far better cache key.