You don't need to work with a form of default image when user not uploaded any image. You can just use a static image when user's avatar
is empty. Just call out a default image
The right way to the set using user default image, you can create a helper method to any helper file like helpers/application.html.erb
def avatar_for(user)
@avatar = user.avatar
if @avatar.empty?
@avatar_user = image_tag("user.png", alt: user.name)
else
@avatar_user = image_tag(@avatar.url, alt: user.name)
end
return @avatar_user
end
if user.avatar
is empty then it will show the default user.png
from assets/images
folder otherwise it will show a user's uploaded the image
and put the image user.png
to assets/images/
folder
Then you can just callout from .html.erb
file like this
<%= avatar_for(current_user) %>
or
<%= avatar_for(@user) %>
#just pass user object from anywhere
Or if you need to show the image with different sizes for a different place then it would be like this
def avatar_for(user, width = '', height = '')
@avatar = user.avatar
if @avatar.empty?
@avatar_user = image_tag("user.png", alt: user.name, width: width, height: height)
else
@avatar_user = image_tag(@avatar.url, alt: user.name, width: width, height: height)
end
return @avatar_user
end
Then callout like this
<%= avatar_for(current_user, 100, 100) %>
Or you can use gravatar
for default avatar
def avatar_for(user)
@avatar = user.avatar
if @avatar.empty?
gravatar_id = Digest::MD5::hexdigest(user.email).downcase
@avatar_user = "https://gravatar.com/avatar/#{gravatar_id}.png"
else
@avatar_user = image_tag(@avatar.url, alt: user.name)
end
return @avatar_user
end
You can see the full tutorial for generating gravatar avatar image from RailsCast