【问题标题】:Using fragment caching in Rails per user每个用户在 Rails 中使用片段缓存
【发布时间】:2014-02-20 19:17:50
【问题描述】:

我有一个列出所有事件的页面。但是事件列表取决于用户是否是管理员。 如果我在迭代视图中的模型对象的页面上使用片段缓存,它将缓存所有事件以供管理员使用。

它可以从缓存中提供给另一个不是管理员的用户吗?如果是,我如何为非管理员和管理员用户使用片段缓存。

【问题讨论】:

  • 根据条件使用 expire_fragment(key, options = nil) 使缓存过期
  • 普通用户都有相同的事件吗?还是根据个人用户创建列表?因为如果它们都不同,那么使用缓存不是最好的主意,因为它只会产生大量的缓存。

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


【解决方案1】:

使用片段缓存键执行以下操作:

<% cache [current_user.role, :events] do %>
  <b>All the Events based on the Current User's Role</b>
  <%= render events %>
<% end %>

http://api.rubyonrails.org/classes/ActionView/Helpers/CacheHelper.html#method-i-cache

您可以在缓存方法的name 参数中传递任意数量的项目,以使缓存适应您的情况。

【讨论】:

    【解决方案2】:

    你可能想做这样的事情:

    <%= cache_unless admin?, project do %>
      <b>All the topics on this project</b>
      <%= render project.topics %>
    <% end %>
    

    从 Rails 文档中提取的示例: http://api.rubyonrails.org/classes/ActionView/Helpers/CacheHelper.html#method-i-cache_unless

    【讨论】:

      【解决方案3】:

      在您的控制器中:

      class ApplicationController < ActionController::Base
      
          fragment_cache_key do
            current_user.role
          end
      
      #...
      

      这将被 Rails 的片段缓存使用并在构造缓存键时添加到fragment_cache_keys 列表中。因此,每当您使用 Rails 的任何片段缓存时,您都会自动为每个用户角色(或在其中使用您喜欢的任何内容)获取唯一的缓存键。

      【讨论】:

        猜你喜欢
        • 2019-12-23
        • 1970-01-01
        • 2016-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-09
        • 2012-01-18
        • 2017-03-04
        相关资源
        最近更新 更多