条件页面缓存
假设我有控制器home_controller.rb
和动作index
。
我想缓存索引页面,所以我正在做:
caches_page :index
但是希望它只为未登录的用户缓存。如果我将条件化为:
caches_page :index, :if => :user_not_signed_in?
页面将在首次未登录用户时缓存。 现在,每个登录用户也会看到未登录的内容。 有没有办法在不更改url的情况下分离此操作?
cache_if和cache_unless现在似乎是正确的方法:
cache_if(condition, name = {}, options = nil, &block) cache_unless(condition, name = {}, options = nil, &block)
你的代码:
<% cache_unless @user.changed?, [ @user, 'form' ] do %>
你想要的东西无法实现;
页面已缓存或未缓存。 该过程检查html文件的存在或处理它。
你还有两种选择:
-
使用动作缓存或片段缓存(不推荐)
-
更推荐:使用ajax加载用户特定的部分,这样你只需要一个页面总是被缓存并且动态插入特定的数据(比如stackoverflow)
以下是最先进的解释: http : //railslab.newrelic.com/scaling-rails
接受的答案现已过时,因为条件缓存现在可用于Rails 4. 拉取请求已合并到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| %> <%= f.label :name %> <%= f.text_field :name %> <%= f.submit %> <% end %> <% end %>