2011-05-30 82 views
6

假设我有控制器home_controller.rb采取行动index有条件页面缓存[解决方案:条件片段缓存]

我想缓存索引页,所以我做的:

caches_page :index 

,但希望它只是缓存未在签约用户如果我要让有条件的,如:。

caches_page :index, :if => :user_not_signed_in? 

页面将被缓存,而首先没有登录的用户来。现在每个登录用户也会看到未登录的内容。有没有办法分开这个动作而不改变url?

回答

1

cache_ifcache_unless似乎是正确的做法,现在做到这一点:

cache_if(condition, name = {}, options = nil, &block) 
cache_unless(condition, name = {}, options = nil, &block) 

您的代码:

<% cache_unless @user.changed?, [ @user, 'form' ] do %>

6

你想要的东西无法实现;

页面被缓存或未被缓存。该过程检查一个html文件的存在或处理它。

还是你有两种选择:建议

  • 使用动作缓存或片段缓存(不推荐)

  • 更多:使用Ajax加载用户特定的一部分,所以你只有一个页面总是缓存和特定的数据动态插入(如计算器)

这里是最先进的解释:http://railslab.newrelic.com/scaling-rails

+0

只是要善待用户不信任JavaScript ;-) – Arsen7 2011-05-30 11:16:57

+3

啊!你的意思是19世纪的用户?那么你是对的这个类别是一个痛苦。 – apneadiving 2011-05-30 11:20:09

+0

是的,JS可能是解决方案。但我会等待一些时间的其他答案:) – dfens 2011-05-30 17:50:39

3

接受的答案是已经过时的,因为条件缓存是现在的Rails 4.提供一个pull requestmerged into 4.0.0rc1,允许:if:unless参数传递给cache。这允许模板变为DRY,因为不再需要复制有条件的缓存块。

用法:

<% cache [ @user, 'form' ], :unless => @user.changed? do %> 
    <%= render partial: 'shared/error_messages', locals: {instance: @user} %> 
    <%= form_for @user do |f| %> 
    <div class="field"> 
     <div><%= f.label :name %></div> 
     <div><%= f.text_field :name %></div> 
    </div> 
    <div class="actions"> 
     <%= f.submit %> 
    </div> 
    <% end %> 
<% end %> 
+0

这对于我来说不适用于<%cache [@questions,@votes],if = > 1 == 0在rails 4.2中执行%>' – Abram 2016-11-08 16:06:21