Reputation: 16212
I have a user model with a has_one_attached :avatar
, using ActiveStorage
.
Avatar is optional, but when it isn't present I want to show a default instead. I store all attachments on Amazon S3, and prefer to store the default there as well.
I'd much prefer if I was able to use variant methods on the default avatar as well.
user.avatar.variant(resize: "100x100")
Any suggestions on how to achieve this? Can I create some sort of default attachment that isn't linked to any specific record and use that when the avatar isn't present?
Upvotes: 6
Views: 3044
Reputation: 715
Instead of attaching the default image, just check if there is an image attached and if not, display the default image. The present?
method will not work in this case, use attached?
instead.
def display_avatar(user)
if user.avatar.attached?
user.avatar
else
'default.png'
end
end
Upvotes: 3
Reputation: 159
There are two methods,
In model use this,(assuming you are using paperclip gem)
:default_url => "/assets/:style/missing.jpeg"
2.Manual
You have to add helper method as below,
def avatar_check user
if user.avatar.image.present?
image_tag user.image_url :thumb
else
image_tag 'default.jpg'
end
end
Save your default.jpg in assets.
In view call below,
User.all.each do |u|
= avatar_check u
And I am not sure about varient
Upvotes: -1