Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To display default user image if image is not present (ruby on rails)

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`
like image 300
SreRoR Avatar asked Sep 18 '25 08:09

SreRoR


2 Answers

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
like image 160
coderhs Avatar answered Sep 21 '25 00:09

coderhs


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.

like image 36
lifejuggler Avatar answered Sep 20 '25 22:09

lifejuggler