我使用此代码在保存帖子更改时清除帖子缓存(在编辑时)
after_commit :flush_cache
def flush_cache
Rails.cache.delete([self.class.name, id])
end
当我添加新评论时,它不会在评论div中显示。但是,当我在这篇文章中做出一些修改时,会出现该评论。
如何在添加新帖子评论时刷新帖子缓存?
达
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :category, touch: true
has_many :comments, dependent: :destroy
.... validations.......
scope :short_listed, -> {....long query here...}
after_commit :flush_cache
def self.cached_short_listed
Rails.cache.fetch([name, "short_listed"], expires_in: 5.minutes) do
short_listed.to_a
end
end
def self.cached_find(id)
Rails.cache.fetch([name,id], expires_in: 5.minutes){find(id)}
end
def flush_cache
Rails.cache.delete([self.class.name, id])
Rails.cache.delete([self.class.name, "short_listed"])
end
def cached_comments
Rails.cache.fetch([self, "comments"]){comments.to_a}
end
def cached_category
Category.cached_find(category_id)
end
def cached_user
User.cached_find(user_id)
end
end