The Hitchhiker’s Guide to Ruby On Rails Galaxy

Records of my voyage through RoR Galaxy

How to force the browser to not cache in Rails

Posted by arjunghosh on April 29, 2008

This is a quick note to self. Though,I found this excellent post by Chad while looking for something else but this post had a excellent note on browser cache also. So this post is mostly a re-post from Chad’s.

So here it goes:

To ensure that the page isn’t cached by the browser and will always be re-fetched, add a before_filter to the purchases controller which calls a private method on ApplicationController:

before_filter :no_cache, :only => [:new]
private
def no_cache
response.headers["Last-Modified"] = Time.now.httpdate
response.headers["Expires"] = 0

# HTTP 1.0
response.headers["Pragma"] = "no-cache"

# HTTP 1.1 'pre-check=0, post-check=0' (IE specific)
response.headers["Cache-Control"] = 'no-store, no-cache, must-revalidate, max-age=0, pre-check=0, post-check=0'
end

Now there is a catch – ‘not caching’ only works in Firefox.

Now the above code should have worked for all browser, but it did not work in Safari or in IE 6 and 7. The reason is that any page with an iframe on it will never be cached, and will always be re-fetched.

The solution is iframe. So, we add this to views/foo/new.

<iframe style="height:0px;width:0px;visibility:hidden" src="about:blank"> this frame prevents back forward cache </iframe>

This frame prevents back forward cache. And this works. Now we have cross-browser no-caching in a RESTful. Though this is a hack as Chad says. But it works for me. :)

About these ads

6 Responses to “How to force the browser to not cache in Rails”

  1. [...] Bernaard wrote an interesting post today onHere’s a quick excerptNow there is a catch – ‘not caching’ only works in Firefox. Now the above code should have worked for all browser, but it did not work in Safari or in IE 6 and 7. The reason is that any page with an iframe on it will never be cached, … [...]

  2. Saniya said

    Hi Arjun,
    Your blogs are very interesting..

  3. arjunghosh said

    Thanks, Saniya for the compliment :)

  4. duecorda said

    it works well for me!

    Thanks =)

  5. arjunghosh said

    thanks @Duecorda. Nice to hear that it helped :)

  6. [...] page is loaded.I’ve created prefilter which set headers preventing caching according to this article but it doesn’t work.Any ideas how to prevent caching?My browser is FF 3.6. [...]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: