Skip to main content

How do I set and use a default image with active storage?

Rails • Asked by Ryan Carter

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
        image_tag 'default_avatar.jpg'

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:'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.

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.