Today when working with images, I have a problem: when an image is absent or has invalid url (404 or so) I need to replace it with asset_path("default_avatar.png")
. So I tried:
def get_url_avatar url
return url if url.present? && Faraday.head(url).status == 200
asset_path "default_avatar.png"
end
But then I found other solution - the onerror
option in image_tag
to handle the problem on the clientside.
The new code:
<%= image_tag (user.avatar),
class: "avatar",
onerror: "this.src='asset_path("default_avatar.png")';" %>
or
<%= image_tag (user.avatar),
class: "avatar",
onerror: "this.src='<%= asset_path("default_avatar.png") %>';" %>
Now I have a new problem with image_tag
. I need to get value of asset_path("default_avatar.png")
in onerror
javascript handler.
But I can't write ruby in onerror
handler. How to do it ?
In erb everything between <%=
and %>
is ruby code, so use ruby string interpolation there:
<%= image_tag (user.avatar),
class: "avatar",
onerror: "this.src='#{asset_path("default_avatar.png")}';" %>