Ask A Question

Notifications

You’re not receiving notifications from this thread.

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

Ryan Carter asked in Rails

If the User does not upload an image using active storage, how do I set a default image for that record?

Reply

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.

Reply

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 master@241bbf2. 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.

Reply

Nice, @eelcoj and @Ali Ahmed. Thanks for sharing.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.