使Rails缓存中的特定模型无效 [英] Invalidate a specific model in the Rails cache
问题描述
我正在使用带有Memcached的Rails 3来缓存某些模型。当模型更改时,我想使该记录的缓存无效。对于视图片段,我只说 expire_fragment( blah)
。如何使用我的模型执行此操作?我不想说 Rails.cache.clear
而全丢了。我想要类似 Rails.cache.invalidate( / users / 5)
之类的东西。我该怎么做?
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?
推荐答案
您没有提到在什么时候实际将模型添加到缓存中。您可以尝试使用 after_save
挂钩使模型缓存无效。
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
这篇关于使Rails缓存中的特定模型无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!