what is a good cache_key?
The docs specify Requires a cache_key method be defined on model: but what constitutes a good cache_key?
def cache_key
"#{self.class.name}-#{self.id}"
end
or
def cache_key
"#{Time.now}-#{self.id}"
end
or
def cache_key
"#{self.class.name}-#{Time.now.to_i}-#{self.id}"
end
It would be nice if the docs provided an example
A key involving the current time would be useless, as even 1 ms later it would be invalid, something like the last updated at time works well instead, if you are wondering how rails defines cache_key for a record, you can see it here: https://github.com/rails/rails/blob/470e6bdac97249ca3406c635f611aa8f7df8b222/activerecord/lib/active_record/integration.rb#L64
Thank for the tips.
So something like this is more appropriate?
def cache_key
"#{model_name.cache_key}/#{self.id}-#{self.updated_at.to_i}"
end
that should work fine, just make sure your cache is set to discards the least recently used when it gets full
Great thanks for your help.
Would you recommend any changes to that method?
Query: @maxrosecollins @ChrisHampel
If you are using this with rails, doesn't active record come with a default cache_key method? Wouldn't this cache_key be used automatically?
https://api.rubyonrails.org/classes/ActiveRecord/Integration.html#method-i-cache_key
Yes, but since Rails 5.2, the cache_key does not include the Timestamp anymore: https://github.com/rails/rails/pull/29092