0

我正在尝试在我的应用程序中使用 Rails 4 缓存摘要,但发现它会干扰很多应用程序逻辑。例如,在这段代码中,@user.id当我有围绕代码的缓存时,应该只显示 current_user 的 id 匹配的链接不能正常工作。任何查看该页面的人都可以看到这些链接。

<% cache @languages do %>
   <% for language in @languages%>

    <tr>
      <td><%= language.name %> </td>


      <% if current_user && current_user.id == @user.id %>
       <td><%= link_to  "edit", {:controller => 'lawyer_profiles', :action =>'show', :language_id =>"#{language.id}"}, {:class => "editarea #{language.id}"}%></td>
      <td><%= link_to "destroy", language, :confirm => 'Are you sure?', :method => :delete %></td>
     <% end %>
    </tr>


    <% end %>


 <% end %>

在这段代码中,缓存干扰了@question 实例变量。例如,由于缓存的存在,当我单击“添加答案”的链接时,它让我回答的@question 与我应该回答的问题不同,因为缓存保留了实例的内存我已经导航离开的页面上的变量。

<% cache @answers do %>
    <% if @answers.empty? %>
    <div class="row">
  <h5>This question hasn't been answered yet:   <% if can? :create, @answer  %>

  <% if current_user && !current_user.answers.map(&:question_id).include?(@question.id) %>
<%= link_to "Add an answer", new_question_answer_path(@question) %>
<% end %>

    <% end %> </h5>
  ....some code not included

如何阻止缓存干扰这样的逻辑?

4

1 回答 1

0

您必须将逻辑添加到缓存键中。所以...

cache [@answers, current_user.answers.map...]

这将基于用户的答案的视图......除了上述内容之外,您可能希望将其余部分分解为更多片段缓存。

于 2013-06-16T00:16:26.367 回答