Conditional Page Caching [Solution: Conditional Fr

2020-03-17 04:50发布

Suppose that I have controller home_controller.rb with action index.

I want to cache index page so I'm doing:

caches_page :index

but want it to cache only for users that are not signed in. If I'll make conditional like:

caches_page :index, :if => :user_not_signed_in?

Page will be cached while first not logged in user comes. Now every logged in user also see not-logged in content. Is there a way to separate this action without changing url?

3条回答
走好不送
2楼-- · 2020-03-17 05:13

cache_if and cache_unless seems to be the correct way to do this now:

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

Your code:

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

查看更多
再贱就再见
3楼-- · 2020-03-17 05:15

What you want couldn't be achieved;

A page is cached or is not cached. The process checks the existence of a html file or process it.

Still you have two alternatives:

  • use action caching or fragment caching (not recommended)

  • more recommended: load user specific part with ajax so you'll only have one page always cached and specific data inserted dynamically (like stackoverflow)

Here are state of the art explanations: http://railslab.newrelic.com/scaling-rails

查看更多
乱世女痞
4楼-- · 2020-03-17 05:27

The accepted answer is now out of date, as conditional caching is now available in Rails 4. A pull request was merged into 4.0.0rc1 that allows for :if and :unless parameters to be passed to cache. This allows templates to be DRY, since there is no longer a need to duplicate the conditionally cached block.

Usage:

<% 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 %>
查看更多
登录 后发表回答