Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalidate a specific model in the Rails cache

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?

like image 283
Paul A Jungwirth Avatar asked Sep 02 '11 14:09

Paul A Jungwirth


People also ask

What is cache line invalidation?

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.

Why do we need to invalidate cache?

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.

How does Rails query cache work?

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.


1 Answers

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
like image 51
dexter Avatar answered Nov 13 '22 04:11

dexter