使Rails缓存失效特定模型

11

我正在使用Rails 3与Memcached来缓存一些模型。当模型发生更改时,我想使该记录的缓存无效。对于视图碎片(View Fragments),我只需要使用expire_fragment("blah")即可。但是对于我的模型,我该怎么做?我不想使用Rails.cache.clear来清空所有缓存。我希望有类似Rails.cache.invalidate("/users/5") 的方法,如何实现呢?

1个回答

24

你没有说明模型实际添加到缓存的时间点。你可以尝试使用 after_save 钩子来使模型缓存失效。

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

谢谢!实际上我只是在寻找Rails.cache.delete方法。当我查看类文档和在控制台中运行Rails.cache.public_methods.sort时,我错过了这个方法。 - Paul A Jungwirth
1
但实际上,我徒劳无功地寻找那种方法,最终让我找到了一个替代方案,描述在这两个链接中:http://koziarski.net/archives/2007/5/28/clever-caching、http://nubyonrails.com/articles/about-this-blog-memcached。在这种方法中,你不直接使缓存失效,而是向缓存键添加额外的内容,确保当对象发生更改时,你可以获得它的最新版本。有时,这与使缓存失效在功能上完全相同,但并非总是如此。 - Paul A Jungwirth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接