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.

15 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! :)

  3. Ed Says:

    Thanks, also saved me a lot of time :)

  4. Zeb Hodge Says:

    I really appreciate you sharing this. It works perfectly.

  5. Tom Says:

    Thanks for this on behalf of usethelist.com! This fixed a couple of bugs that were showing up in IE. Makes me happier every day to see web sites like ie9countdown.com. Thanks again!

  6. Swartz Says:

    Thanks. Saved me at least an hour for sure.

  7. Jeff Says:

    I also thank you. Solved an issue for me yesterday.

  8. Joel Says:

    Thanks for this post, helped a lot.

  9. Clint Says:

    I’m a little late to the party, but this information really saved me from a lot of grief and frustration. I’m actually surprised this topic is not talked about more considering there are so many rails/ajax sites now. The problem and your solution seems so obvious in hindsight, but not until I found your solution so thank you very much for sharing!

  10. Sandip Says:

    Thanks a lot. You just saved my time….Thanks again…

  11. Monty Says:

    Oh thanks so much saved my day … thanks bro :)

  12. Narasppa Says:

    Thanks a lot it saved a lot of time ..but some time time gives error when header has parameter values..

  13. Relief Says:

    Thanks a bunch!

  14. Chirag Says:

    This works perfectly. It’s very helpful.

  15. santosh Says:

    Thanks a lot, it works fine in all the browsers but not affecting in Safari.

Leave a Reply