Reputation: 575
I am trying to set a default image for users when they sign up. They can change that if they prefer and otherwise a default image will be given. The input_html
, however, doesn't seem to work?
How can I set a default image?
Current simple form for input:
<% default_picture = (image_path 'user.png') %>
<%= f.input :avatar, input_html: {value: '#{default_picture}'}, label: false %>
Upvotes: 0
Views: 4961
Reputation: 7777
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
Upvotes: 1
Reputation: 61
you can use before_create
in your model, to set the default image.
before_create :set_default_avatar
def set_default_avatar
# your code
end
and here other discussion regarding about your question, Rails - What is the best way to display default avatar if user doesn't have one?
Upvotes: 3