简体   繁体   中英

Use javascript to replace broken image of a particular tag in Ruby On Rails views

I want to show the avatar of a user in a view, but the image is sometimes missing, hence the missing.png is showed instead. How do I replace it with a default image? (Note: I don't want to replace all broken images in the view with it, just the one I'm interested in).

I've done some googling and found this javascript function, but not sure how to use it in my view ( .html.havl file) (I'm VERY new to Ruby on Rails)

$('img').error(function(){
 $(this).attr('src', '<<<REPLACE URL>>>');
});

Here's my view

...
.user_avatar
 %img{:src => @user.avatar.url} <<<< how do I make the 'src' points to the default image 
...

Just use a more specific selector on the JS side:

$(".user_avatar img").on('error', function () {
    $(this).attr('src', 'replace-url');
});

If you want to do this on the RoR side, you can check that @user.avatar.url exists if it's on the same filesystem or even using an HTTP request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM