【问题标题】:Rails 4 Fragment Cache Entire Page. How to Expire Cache In ModelRails 4 片段缓存整个页面。如何使模型中的缓存过期
【发布时间】:2016-02-12 16:28:17
【问题描述】:

如何使模型中的主页片段过期?

在我的 HTML 中

<% cache 'main-page' do %>
  # html here
<% end %>

在我的帖子模型中

after_create :clear_cache
after_update :clear_cache

def clear_cache
  ActionController::Base.new.expire_fragment('main-page')
end

这不会清除缓存。如果我创建或更新帖子,缓存不会清除。如果我在 Rails 控制台中运行ActionController::Base.new.expire_fragment('main-page'),它会返回“nil”。如果我在 post 模型中运行 Rails.cache.clear 而不是 ActionController::Base.new.expire_fragment('main-page'),它可以工作。

【问题讨论】:

    标签: ruby-on-rails-4 caching fragment-caching


    【解决方案1】:

    我相信您的问题是摘要,因此如果您将缓存更改为此它应该可以工作:

    <% cache 'main-page', skip_digest: true do %>
      # html here
    <% end %>
    

    如果您想使用这种样式,其中缓存不会过期并且依赖于检测模型更改来使无效,您可能需要考虑使用从 Rails 4 中删除但很有用的 Observer 或 Sweeper对于这种模式:

    https://github.com/rails/rails-observers

    也许不是您正在寻找的答案,而是另一种方式:

    根据 Post 模型中的 max updated_at 创建缓存键。

    每当任何帖子更改时,缓存键都会自动丢失并检索最新帖子以重新缓存该部分视图。

    module HomeHelper
      def cache_key_for_posts
        count          = Post.count
        max_updated_at = Post.maximum(:updated_at).try(:utc).try(:to_s, :number)
        "posts/all-#{count}-#{max_updated_at}"
      end
    end
    

    然后在你看来:

    <% cache cache_key_for_posts, skip_digest: true do %>
      # html here
    <% end %>
    

    【讨论】:

    • 好的,据我了解,您的第二个选择是“正确的方式”。我明白了,但第一个选项要简单得多。
    • 第二个选项将视图缓存与您的模型清晰地分开,但它也会命中数据库以生成该密钥,因此需要权衡取舍。它与带有俄罗斯娃娃缓存的 Rails 4 缓存样式更一致,但是,嘿,这是你的应用程序。如果您要执行选项 1,则可以考虑使用观察者或清扫器 github.com/rails/rails-observers 将该代码排除在模型之外。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 2015-03-11
    • 2013-01-14
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2015-01-01
    相关资源
    最近更新 更多