fast_jsonapi icon indicating copy to clipboard operation
fast_jsonapi copied to clipboard

what is a good cache_key?

Open maxrosecollins opened this issue 7 years ago • 6 comments

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

maxrosecollins avatar Jan 24 '19 17:01 maxrosecollins

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

ChrisHampel avatar Jan 24 '19 19:01 ChrisHampel

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

maxrosecollins avatar Jan 24 '19 20:01 maxrosecollins

that should work fine, just make sure your cache is set to discards the least recently used when it gets full

ChrisHampel avatar Jan 25 '19 07:01 ChrisHampel

Great thanks for your help.

Would you recommend any changes to that method?

maxrosecollins avatar Jan 25 '19 10:01 maxrosecollins

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

sumeetattree avatar Feb 16 '19 15:02 sumeetattree

Yes, but since Rails 5.2, the cache_key does not include the Timestamp anymore: https://github.com/rails/rails/pull/29092

iv-mexx avatar Mar 12 '19 18:03 iv-mexx