Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails how to delete cache key using partial match

I am using redis-rails. For cache key I am using an array:

Rails.cache.fetch([self.class.name, :translated_attribute, id, field, I18n.locale]) do
  self.read_attribute field, locale: I18n.locale
end

Now I need to remove all the cache with key matches with [self.class.name, :translated_attribute, id]. I know it has delete_matched that takes wildcard(*) after key for partial matching.

But I dont know what is the exact key generated. Now I need to know how it makes the key when we use array as key. I mean if I use [:foo, :bar, :dum] as cache key what will be the exact key in cache store?

like image 392
Muntasim Avatar asked Oct 26 '13 06:10

Muntasim


1 Answers

The default rails cache key format is: [class]/[id]-[timestamp]

i usually dont use rails default cache key format, instead i create my own keys so it would be easier to manipulate in redis.

cache_key = "#{self.class.name}/#{translated_attribute}/#{id}/#{field}/#{I18n.locale}"

Rails.cache.fetch(cache_key) do
  self.read_attribute field, locale: I18n.locale
end

Rails.cache.delete(cache_key)
Rails.cache.delete_matched("#{self.class.name}*#{id}*")
like image 106
joreal Avatar answered Oct 31 '22 18:10

joreal