I want to write a condition in ruby to display default image if no user image is present , if present display the present image.
This is my index.html.slim page:
@product.reviews.each do |r|
a href="#"
= image_tag r.user.image_url :thumbnail`
I recommend you add the code for that in the helper or model, to keep the code clean.
helper method:
def user_avatar user
if user.image.present?
image_tag user.image_url :thumbnail
else
# Assuming you have a default.jpg in your assets folder
image_tag 'default.jpg'
end
end
view page:
@product.reviews.each do |r|
a href="#"
= user_avatar r.user
Also, from the code i feel like you are using a library like paperclip or carrierwave.
If so in paperclip you can set the default image by placing this code in the model.
:default_url => "/assets/:style/missing_avatar.jpg"
if you are using carrierwave place this method in your uploader file.
def default_url
"/images/fallback/default.png"
end
Assuming that you are using paperclip or something to save your images to the database, you can check if image exists by having
if r.user.image.present?
= image_tag r.user.image_url :thumbnail
else
= image_tag 'your default image path'
end
you should check your image gem to get find out whether this is valid as I don't know what kind of setup you have.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With