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,nly => [: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.


fire » Blog Archive » How to force the browser to not cache in Rails said
[...] 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, … [...]
Saniya said
Hi Arjun,
Your blogs are very interesting..
arjunghosh said
Thanks, Saniya for the compliment
duecorda said
it works well for me!
Thanks =)
arjunghosh said
thanks @Duecorda. Nice to hear that it helped
Issue with iframe caching? - Question Lounge said
[...] 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. [...]