1

In Rails 3 (with Chrome), I set a flash, call redirect_to, and so send the browser back to a page which the user has been on before.

However, Chrome does not render this page; rather, Chrome takes it from the cache. This means, for example, that the flash is not rendered.

I could add a random param to the URL to make sure the cache is not used, but this is clumsy.

How do I make sure that the page I am redirecting to is re-rendered?

Joshua Fox
  • 15,727
  • 14
  • 65
  • 108

1 Answers1

1

There's a couple of ways i can think of to do this: meta http-equiv tags or http headers.

Method A) meta http-equiv

Add the following to the head section of your template.

<% if @prevent_caching %>
  <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/>
  <meta http-equiv="Pragma" content="no-cache"/>
  <meta http-equiv="Expires" content="0"/>
<% end %>

then, in any controller action you can say @prevent_caching = true before rendering the page.

This seems a bit clumsy, and i believe meta http-equiv can be unreliable. Hence...

Method B) http headers. This is a much more direct and reliable way of telling the browser not to cache: see How to control web page caching, across all browsers?

I would put them in a protected method in your ApplicationController, which will let you call it from any other controller (since they all inherit from this)

#in app/controllers/application.rb
protected
def prevent_browser_caching
  response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate' # HTTP 1.1.
  response.headers['Pragma'] = 'no-cache' # HTTP 1.0.
  response.headers['Expires'] = '0' # Proxies.
end

Then, it's like before except you call the method instead of setting a variable.

#in the controller where you don't want the response to be cached
prevent_browser_caching
Community
  • 1
  • 1
Max Williams
  • 30,785
  • 29
  • 115
  • 186