我正在使用Rails 3与Memcached来缓存一些模型。当模型发生更改时,我想使该记录的缓存无效。对于视图碎片(View Fragments),我只需要使用expire_fragment("blah")
即可。但是对于我的模型,我该怎么做?我不想使用Rails.cache.clear
来清空所有缓存。我希望有类似Rails.cache.invalidate("/users/5")
的方法,如何实现呢?
我正在使用Rails 3与Memcached来缓存一些模型。当模型发生更改时,我想使该记录的缓存无效。对于视图碎片(View Fragments),我只需要使用expire_fragment("blah")
即可。但是对于我的模型,我该怎么做?我不想使用Rails.cache.clear
来清空所有缓存。我希望有类似Rails.cache.invalidate("/users/5")
的方法,如何实现呢?
你没有说明模型实际添加到缓存的时间点。你可以尝试使用 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