Rails 5.2: Upload attachments using Active Storage

Mayur Kambariya
Techcompose
Published in
3 min readMay 15, 2019

From many years, we are using libraries like Paperclip, CarrierWave, and Shrine to upload attachments for a rails application. But since the deprecation of paperclip in rails 5.2, I think we need to start using the Active Storage.

Why Active Storage?

Active Storage allows you to easily handle the file uploading either to cloud like Amazon S3, Google Cloud Storage or in your Application directory and linking it with the Active Record models. It’s a new feature released in version 5.2.

Let’s start implementing the Active storage from scratch in rails application.

1)Create new rails application using below command

rails new tc-active-storage

If you want to use a specific database for the application

rails new tc-active-storage -d=<database name>

2) Go to tc-active-storage folder

3) Run command bundleor bundle install

4) Run below command to generate migration and install active storage in your App

rails active_storage:install

A command for install active storage

5) Now in the application folder, you see active storage migration file

Migration file
Migration file and its fields

After execution is over, it creates two tables that Active Storage needs to deliver on its promises: active_storage_attachments and active_storage_blobs

6) To store the attachment we need to create a Model and add Active Storage relationship

has_one_attached:image (If single image)

Or

has_many_attached:image (If multiple images)

7) Inside Controller permit image params

For a single image:

Just pass as like a single element

For multiple images:

Permit as array
multiple: true is HTML property for file input

Important Notes:

Model: We called has_one_attached or has_many_attached method in the model definition with a symbol that will become a virtual attribute on each instance of our model.

Controller: We white listed image parameter

Views: We added a file_field to our form and displayed an uploaded image in the image_tag.

Image variants with ImageMagick

You may give any size variants here

image.variant(resize:"500x500", momochrome:true)

How to configure with cloud for upload attachments

config/storage.yml

Storage file for configuring different cloud

For local

config/environments/development.rb

For production

config/environments/production.rb

Active Storage cloud configuration

Congratulations, you have successfully applied the Active Storage to your Rails application.

Contact Ruby on Rails Development Company to develop your Business mobile app or web application with elegant design. Contact us to Hire dedicated ROR developer today or reach us at inquiry@techcompose.com for any assistance regarding larval development requirement.

--

--