I'm using Rails 3 with Memcached to cache some models. When the model changes, I want to invalidate the cache for that record. With view fragments, I just say expire_fragment("blah")
. How do I do this with my models? I don't want to say Rails.cache.clear
and lose the whole thing. I want something like Rails.cache.invalidate("/users/5")
. How do I do that?
Invalidation of a cache or cache line means to clear it of data. This is done by clearing the valid bit of one or more cache lines. The cache must always be invalidated after reset as its contents will be undefined. If the cache contains dirty data, it is generally incorrect to invalidate it.
Cache invalidation can be used to push new content to a client. This method functions as an alternative to other methods of displaying new content to connected clients. Invalidation is carried out by changing the application data, which in turn marks the information received by the client as out-of-date.
Query caching is a Rails feature that caches the result set returned by each query. If Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.
You did not mention at what point the model is actually added to the cache. You could try invalidating the model cache using the after_save
hook.
class Model < AR::Base
after_save :invalidate_cache
private
def invalidate_cache
Rails.cache.delete("/users/#{self.id}")
return true # recommended to return true, as Rails.cache.delete will return false if no cache is found and break the callback chain.
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With