俄罗斯娃娃缓存和隐藏敏感链接

Russian Doll caching and hiding sensitive links

我们如何在缓存视图时隐藏敏感的或用户特定的链接,例如 'Edit' 或 'Delete' 按钮?

使用缓存时,不能真正使用条件语句,例如:

<% if current_user.can? edit %>
  <%= link_to 'Edit', edit_post_path(@post) %>
<% end %>

因为所有观众都将看到相同的页面。

一些教程告诉我可以这样使用 CSS:

<% if current_user.can? edit %>
  <%= link_to 'Edit', edit_post_path(@post), class: 'admin-link' %>
<% end %>

但是我该如何验证编辑权限?

您可以将那部分添加到缓存键中,例如

<% cache [@post, current_user.can? :edit] do %>
  <% if current_user.can? edit %>
     <%= link_to 'Edit', edit_post_path(@post) %>
  <% end %>
<% end %>

只需确保处理用户未登录的部分,您可以将其发送到控制器的变量中,例如

@can_edit = user_signed_in? && current_user.can? :edit

那么在视图中就会变成

<% cache [@post, @can_edit] do %>

这样 rails 将生成两个缓存,一个给可以编辑的人,一个给不能编辑的人,并为正确的用户呈现每个缓存。