11

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?

Paul A Jungwirth
  • 23,504
  • 14
  • 74
  • 93

1 Answers1

24

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
Roland Studer
  • 4,315
  • 3
  • 27
  • 43
dexter
  • 13,365
  • 5
  • 39
  • 56
  • Thanks! Actually I was just looking for the Rails.cache.delete method. Someone I missed this when I checked the class docs and again when I ran Rails.cache.public_methods.sort in the console. – Paul A Jungwirth Sep 05 '11 at 20:07
  • 1
    But actually, my vain search to find that method led me to an alternate approach, described at these two links: http://koziarski.net/archives/2007/5/28/clever-caching, http://nubyonrails.com/articles/about-this-blog-memcached, where instead of invalidating the cache directly, you just add something extra to the cache key that ensures when the object changes, you get its most recent version. Sometimes this is functionally identical to invalidating your cache, but not always. – Paul A Jungwirth Sep 05 '11 at 20:10