Using Active Storage To Handle Image Uploads In Ruby On Rails

Using Active Storage To Handle Image Uploads In Ruby On Rails

Active Storage is a framework that handles file uploads, allowing you to store them as attachments locally or on a third-party cloud storage service (like Amazon s3 or Microsoft Azure Storage). It then links those attachments to an Active Record object.

Active Storage isn’t just useful for storing images — it can also generate image representations for non-image uploads, such as videos or PDFs. By combining it with ImageMagick, you can even manipulate image uploads. For now, I just want users to upload a profile picture when they register, and for my app to store that picture locally.

Setting up Active Storage

To begin implementing Active Storage, I opened up the Rails dating application I had already created. Then, I ran rails active_storage:install. This created a migration file that set up two tables, active_storage_attachments and active_storage_blobs.

Active Storage stores information about each file — such as filename, size, and metadata — in active_storage_blobs. active_storage_attachments is a join table that connects those blobs to a model (in this case, my user model). Active Storage’s polymorphic associations spare me from having to add columns to the models I already created. I used rails db:migrate to run this migration.

Adding Active Storage To A Model

To add an Active Storage association to a model, I added has_one_attached:profile_pic to my user.rb model. If I was storing multiple user images, I would’ve used has_many_attached:image alternatively.

Now in user registration_controller.rb file, I added the following code to update method

Configuring Active Storage

Next, I had to indicate where images would be stored. If I was using Amazon s3 or Google Cloud, this is where I’d declare those services. I chose to store my files locally so in config/storage.yml, I added:

Then, in config/environments/development.rb, I added config.active_storage.service = :local within Rails.application.configure do:

Allowing Users To Upload On The Front-End

Finally, I added a file upload field to my pre-existing user registration form.

I added a new f.label and f.file_field for :profile_pic, which inserted a “Choose File” button within the form. Clicking “Choose File” opens a Finder/File Explorer window where the user can select a profile image on their device.

Displaying User Images

Once the user successfully upload the profile picture, I would display the image as shown below

Leave a Reply

Your email address will not be published. Required fields are marked *