如何阻止缓存干扰应用程序逻辑

时间:2013-06-15 23:49:22

标签: ruby-on-rails

我正在尝试在我的应用中使用Rails 4缓存摘要,但我发现它会干扰很多应用程序逻辑。例如,在此代码中,当我拥有围绕代码的缓存时,应该仅显示current_user的id与@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

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

1 个答案:

答案 0 :(得分:0)

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

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

这将基于用户的答案的基础...你可能想要将其余的分解为更多片段缓存以及上述内容。