俄罗斯娃娃缓存用户特定内容

时间:2012-08-28 22:51:21

标签: ruby-on-rails ruby ruby-on-rails-3 caching heroku

我想做一些沉重的缓存(DHH称之为俄语玩偶缓存),但我不知道该怎么做,因为我有很多内容取决于用户和他拥有的属性。

你会如何在这样的视图上做RDC?:

<% if signed_in? %>
  <div class="timeline">
    <%= link_to image_tag(current_user.avatar), designer_path(current_user), :class => "avatar topimg" %>
    <%= content_tag(:span, "your profile", :class => "description") %>
    <%= link_to "", new_design_path, :class => "upload icon-upload" %>
    <%= content_tag(:span, "upload a new design", :class => "description") %>
    <%= link_to "", designer_path(current_user)+"/favorites", :class => "upload icon-star" unless current_user.followees_by_type("design").blank? %>
    <%= content_tag(:span, "designs you've favorited", :class => "description") unless current_user.followees_by_type("design").blank? %>
    <%= content_tag(:span, current_user.current_invites, :class => "invites_count") unless current_user.current_invites <= 0 || current_user.full_member == false %>
    <%= link_to "", "#", :class => "invite icon-plus "+("blue" unless current_user.current_invites == 0).to_s unless current_user.current_invites < 0 || current_user.full_member == false  %>
    <%= content_tag(:span, "invite a friend ("+current_user.current_invites.to_s+" invites left)", :class => "description") unless current_user.current_invites < 0  %>
    <%= content_tag(:span, activity, :class => "activity_count") unless activity == 0 %>
    <%= link_to "", designer_path(current_user)+"/statistics", :class => "upload icon-activity "+("blue" unless activity == 0).to_s unless activity == 0 %>
    <%= content_tag(:span, ("your activity ("+pluralize(activity, 'new thing')+")"), :class => "description") unless activity == 0%>
  </div>
<% else %>
  <%= link_to raw('<i class="icon-twitter icon-font"></i><span>login with twitter</span>'), "/auth/twitter", :class => "btn btn-twitter grey-tweet" %>
<% end %>

1 个答案:

答案 0 :(得分:0)

您可以将整个事物包装在一个大缓存块中,如下所示:

<% cache ['timeline', @user] do %>
  ...
<% end %>

这将使用密钥timeline /#{@user.cache_key}对其进行缓存。 cache_key默认包含记录ID和updated_at,因此一旦用户记录更新,缓存的片段将自动失效*。

请注意,如果您在片段中使用关系(例如关注者),则每次更新其中一个关系时都应触摸用户对象。这可以通过设置自动完成:touch =&gt;关于这种关系的确如此:

class Follower
  belongs_to :user, :touch => true
  ...

(*)请注意,过时的缓存密钥并非真正失效,它将不再使用。您应该在所有缓存键上设置一个到期日期或进行一些常规内务处理,以避免溢出缓存。