【问题标题】:Conditional Page Caching [Solution: Conditional Fragment Caching]条件页面缓存【解决方案:条件片段缓存】
【发布时间】:2011-09-04 15:33:15
【问题描述】:

假设我有控制器 home_controller.rb 和动作 index

我想缓存索引页所以我在做:

caches_page :index

但希望它只为未登录的用户缓存。如果我将条件设为:

caches_page :index, :if => :user_not_signed_in?

当第一个未登录的用户到来时,页面将被缓存。现在每个登录的用户也可以看到未登录的内容。有没有办法在不改变 url 的情况下分离这个动作?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 caching


    【解决方案1】:

    你想要的无法实现;

    页面已缓存或未缓存。该进程检查是否存在 html 文件或对其进行处理。

    你还有两个选择:

    • 使用动作缓存或片段缓存(不推荐)

    • 更推荐:使用 ajax 加载用户特定部分,这样您就可以始终缓存一页并动态插入特定数据(如 stackoverflow)

    以下是最先进的解释:http://railslab.newrelic.com/scaling-rails

    【讨论】:

    • 善待不信任 JavaScript 的用户 ;-)
    • 啊!你是说 19 世纪的用户?嗯,你是对的,这个类别很痛苦。
    • 是的,js 可能是解决方案。但我会等待其他答案一段时间:)
    • 这不是我建议的唯一解决方案:动作和片段缓存在您的情况下工作正常
    • 好的,我接受这个答案。同时,我创建了一个 gem 来满足条件缓存 github.com/dfens/active_cache ,这仍在大量维护中,但可能是一个解决方案
    【解决方案2】:

    现在接受的答案已经过时,因为 Rails 4 中现在可以使用条件缓存。pull requestmerged into 4.0.0rc1,它允许将 :if:unless 参数传递给 cache。这允许模板是 DRY,因为不再需要复制有条件缓存的块。

    用法:

    <% cache [ @user, 'form' ], :unless => @user.changed? do %>
      <%= render partial: 'shared/error_messages', locals: {instance: @user} %>
      <%= form_for @user do |f| %>
        <div class="field">
          <div><%= f.label :name %></div>
          <div><%= f.text_field :name %></div>
        </div>
        <div class="actions">
          <%= f.submit %>
        </div>
      <% end %>
    <% end %>
    

    【讨论】:

    • 这对我在 rails 4.2 中的 &lt;% cache [@questions, @votes], :if =&gt; 1==0 do %&gt; 不起作用
    【解决方案3】:

    cache_ifcache_unless 现在似乎是正确的做法:

    cache_if(condition, name = {}, options = nil, &block)
    cache_unless(condition, name = {}, options = nil, &block)
    

    您的代码:

    &lt;% cache_unless @user.changed?, [ @user, 'form' ] do %&gt;

    【讨论】:

      猜你喜欢
      • 2015-08-05
      • 2011-03-01
      • 2016-04-11
      • 1970-01-01
      • 2023-03-29
      • 2011-05-11
      • 2010-11-05
      • 1970-01-01
      • 2013-10-18
      相关资源
      最近更新 更多