If the User does not upload an image using active storage, how do I set a default image for that record?
Easiest way is to use a view helper and put the logic in there.
Something along the lines of:
def user_avatar(user_id) user = User.find!(user_id) if user.avatar.attached? image_tag user.avatar else image_tag 'default_avatar.jpg' end end
Jack, thanks for the reply. I considered that way, but I need something in the database for error issues and for my meta tags. I will probably just make that a required item and use some validations. Thanks again for the help.
Since ActiveStorage released in a very recent version of rails. I faced a lot of issues when I had to play with it customly. I checked a lot of PRs and tried to contribute. Many of them are only in Edge Guides, based on [email protected]. Any ways, active storage works with having separate entities in your db with two tables blobs and attachments. When ever we attach items to model it associates the model with ActiveStorage::Attachment model and stores the file object in to the ActiveStorage::Blob model. I reckon that what if you initially attach a default image to user's object on the first time when the user is created. You can set the image in a method in your User model and do this (if you know already):
self.image.attach(io: File.open(Rails.root.join('app', 'assets', 'images', 'placeholder-icon.png')), filename: 'default-image.png', content_type: 'image/png')
and setting this in your before_create callback.
Hope this helps. I know there could be a better way in contrast to mine but this will set a default image nevertheless of having the traditional helper methods approach.
Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.