I am using Rails ActiveStorage. I want that whenever the value of attachment (in my case image is null then replace it with "abc.png" which is present in assets folder..)
This is what my model.rb file looks like but this code does not seem to work. I am looking for how to set default / nil value for avatar.
has_one_attached :avatar #bot icon
after_create_commit check_avatar(self)
def check_avatar(self)
if(!self.avatar.present?)
{
self.avatar = "abc.png"
}
end
Active storage doesn't provide default option like paperclip does, however, you can do write your method to attach default file in case image is nil. you can use attach method to do so.
def image_nil
if !self.image?
user.image.attach(io: File.open('/path/to/file'), filename: 'file.pdf', content_type: 'image/jpeg')
end
end
you can omit content_type but it is good to provide it, the content type you provide will serve as a fallback in case analyzer can't do it.
Hope this helps!