Whats the best way to create an image_tag(via the rails helper) that displays another image if the default one is broken instead of text. It doesn't have to support recursion. I just have a default image I want to use if a link is broken.
-
There's a neat way to do this if you're using Carrierwave to upload photos. – Elvn Jun 03 '15 at 21:05
3 Answers
You can do this via JS, here shown as jQuery:
$('img').error(function() {
$(this).attr('src', 'missing.png');
});
If it's a specific image you could attach the error handler to just that object.
I don't know of any way to do this via the image_tag
helper; you'd have to make a request from the app to the src URL and check for an error. I'd make sure that's actually what you need to do before going down that road, though, but it depends on your requirements.

- 158,873
- 26
- 254
- 302
-
-
@Helsing I wouldn't discount the CSS idea, although I've never tried it with any real success. – Dave Newton Jun 03 '15 at 19:40
I struggle with similar kind of problem where I have inside table several thumbnail pictures and I needed to checked if that picture is missing then show default image.
For this I use image_tag with helper method. In helper method I check with File.exist? if file exist. If it was then I returned path to image as a string to image_tag else I returned path to default image.

- 1