Document how to expire cache manually
sometimes i want to expire(remove) cache manually. for example,
in rails console: val = ValueModel.fetch(1) (and log shows like that.. SQL: select * from value_model where id = 1 limit 1)
and this record is updated at other environment(ex: raw sql from DBMS)
then, use statement again in rails console. val2 = ValueModel.fetch(1) and then rails console shows, cache hit, and nothing changed.
in this situation, can i expire this cache manually?
When a record is saved, expire_cache is the method called on it to expire the cache keys for it. That includes:
- the primary index key for the record
- the primary index for parent records that embed the record
- cached attributes, including for secondary indices
If you are trying to load the record (e.g. because the raw SQL update is for performance reasons) then there is an expire_primary_key_cache_index(id) class method on the model that can be used to expire just the primary index for that record. If the record is embedded in parent records, the same method could be used on the parent model to expire records that embed it. There isn't currently a class method exposed to expire cached attributes, but we would be open to adding that if it were needed.
@dylanahsmith thank you. but sadly i use version 0.5.1 because of ruby version issue. and i can`t use expire_primary_key_cache_index.
so i used some workaround because method expire_cache if private 👯♂
if variable "target" is invalid cache,
cache_key = target.primary_cache_index_key IdentityCache.cache.delete(cache_key) #cache expired. in this case, i need to expire primary index only.
I find there is rails_cache_key in the class, so we could expire the cache without loading the model!
IdentityCache.cache.delete(MyModel.rails_cache_key(my_id))
If you are on the latest version of the code, then MyModel.expire_primary_key_cache_index(my_id) can be used.
Oh right, I meant to leave this open to remember to document this. Updated the title accordingly