Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop images from caching in Rails and browser?

I have created a image crop facility that I can click on an image and crop it and it saves the new cropped image over the old one, then redirects back to the original page where the image was show.

But it still shows the old image even after a redirect and doesn't display the new one till I refresh the page.

I have tried just using an image tag and removing the asset timestamp after the image but it still displays the old image and I have also tried adding meta tags to stop browser caching but not working.

How can I solve this without having to do a refresh page?

like image 276
richard moss Avatar asked Feb 28 '23 22:02

richard moss


2 Answers

It's probably not the best way, but I've solved this problem in the past by simply appending a timestamp to the image URL using JavaScript:

http://www.mysite.com/img/some_image.jpg?timestamp=12342312412

Next time it loads, the timestamp is set to the current time and the URL is different, so the browser does a GET for the image instead of using the cached version.

like image 55
Kaleb Brasee Avatar answered Mar 07 '23 21:03

Kaleb Brasee


Are you using the rails image helper tag: image_tag in your views?

Rails automatically appends a timestamp based on the last modified date of the image file which is handy because it should change when you do your crop and write out the new image.

More information in the docs: http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html

like image 42
Mike Buckbee Avatar answered Mar 07 '23 22:03

Mike Buckbee