Search code examples
ruby-on-railsrubyif-statementfile-exists

How do I create a default avatar if the avatar file does not exist?


I used paperclip to let users upload their avatars. Everything works fine.

I want to show a default image if the user didn't upload an avatar. I used this code in my view:

<%= 
    if File.exist?(user.avatar.url)
         image_tag user.avatar.url(:large)
    else
         image_tag "default-avatar.png"
    end
%>  

but it doesn't show the default image.

I put the default-avatar.png in app/assets/images/. What am I doing wrong?

EDIT

I followed the instructions oldergod mentioned in comments, but still the uploaded avatars don't show up.


Solution

  • I finally put it to work, using user.avatar? like this:

    <%= 
       if user.avatar?
          image_tag user.avatar.url(:large)
       else
          image_tag "default-avatar.png"
       end
    %>  
    

    I think the problem is that File.exist? needs a path, not a url or something.