How to prevent browsers from caching a page in Rails

Tuesday, April 14th, 2009

This took me forever to figure out, so I hope I’ll be able to save someone a few hours of annoyance someday.

Serendeputy is always recalculating, and I needed to make sure that the browsers wouldn’t cache the page when someone clicked off and then hit the back button. This is how I was able to do it.


..in application_controller.rb..
  before_filter :set_cache_buster
  def set_cache_buster
    response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
  end

I just tested this out, and it works on Safari and Firefox on the Mac, and IE7, Firefox and Chrome on the PC.

Hope this helps.

2 Responses to “How to prevent browsers from caching a page in Rails”

  1. Eric Kramer Says:

    Thanks, this saved me a bunch of effort. I appreciate that you shared this!

  2. Shripad Says:

    Thanks a ton! :)

Leave a Reply