rails从片段缓存中遗漏了一些部分

我有一个使用pundit gem进行授权的rails 4 app。 如果我像下面的代码那样执行俄语 – 娃娃片段缓存,则用于授权的条件语句也将被缓存,这是不好的,因为编辑/删除按钮应仅适用于post.user

解决这个问题的好方法是什么? 我应该将缓存拆分成更小的部分,还是有办法排除缓存的某些部分? 在这种情况下,轨道惯例是什么?

index.html.erb

    

_post.html.erb

  
<div class="col-md-12 post-comment-insert-">
<div class="modal fade updatepost" id="updatepost_" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal fade" id="deletepost_" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> ......

俄罗斯娃娃缓存是一种简单但方便的缓存方式,没有复杂的选项或约定来从中排除部分片段。 在此之上,它更多地与缓存策略相关。 以下是针对此用户特定情况的两种策略:

  1. 单独重新排列和手动缓存片段,我不建议这样做。 因为它更复杂,并没有利用俄罗斯娃娃缓存的优势。 也不是那么可维护。 这是一个例子:

index.html.erb

 <% # pull out cache %> <%= render @posts %> 

_post.html.erb

 <% cache post %> <%= # first part %> <% end %> <% # without cache %> <%= # user specific part %> <% cache post %> <%= # third part %> <% end %> 
  1. 首选方法:将current_user添加为cache_key一部分,这意味着您将拥有与用户大致相同的片段缓存,并且只要post或用户更改了指纹,片段就会自动失效。 这更优雅,更易于维护。 这是一个例子:

index.html.erb

 <% cache ["posts-index", @posts.map(&:id), @posts.map(&:updated_at).max, @posts.map {|post| post.user.profile.updated_at}.max] do %> <%= render @posts %> <% end %> 

_post.html.erb

 <% cache ['post', post, post.user.profile, current_user ] do %> 
<%= link_to user_path(post.user) do %> <%= image_tag post.user.avatar.url(:base_thumb), class: 'post-avatar' %> <% end %>
<%= post.user.full_name %> <%= local_time_ago(post.updated_at) %>
<%= post.body %>
<% if policy(post).edit? && policy(post).delete? %> <% end %>
<%= render partial: 'posts/post_comments/post_comment_form', locals: { post: post } %>
<%= render partial: 'posts/post_comments/post_comment', collection: post.post_comments.ordered.included, as: :post_comment, locals: {post: post} %>
<% if policy(post).edit? %> <% end %> <% if policy(post).delete? %> <% end %> <% end %>
Interesting Posts