Getting started with Rails Active Storage

Getting started with Rails Active Storage

29 Sep 2022
Getting started with Rails Active Storage

Storing the static files in Rails is an important specification achieved by third-party gems (like Paperclip or CarrierWave). Rails, then, introduced the idea of Active Storage in Rails 5.2, which reduces the use of third-party gems required for storing static files and provides an easy way to store them.

Get Started with Active storage:

To start with Active Storage, create a new application or simply run the following command in the existing rails application with the help of the command line or in the terminal:

Run the migrate command to display the migration file in the database. After running the above-mentioned command, Rails will create a migration file. While inspecting the generated migration file, it will show 2 different tables created by running the command. First is the active_storage_blobs, which contains data files like checksum, filename and so on.

The following table showcases active_storage_attachments, a polymorphic association, which stores file attachments and records.

The below-mentioned code has to be added to the config/storage.yml file:

This code makes sure that all the assets are stored on the local system or disk. It provides options to configure Active Storage with other storage services like Azure. For this process, we will proceed with the local system.

Declare Attachment Associations:

With the database ready to get connected with any Active Record model (i.e., with an uploaded image), it is time to declare associations in the models. If the user wants the model to have one image attached to it, then it is important to declare some variety of elements in the model:

The above code will make sure that the model will get attached to an image. If the user wants to attach multiple images, add the code: — has_many_attached:images.

With the model now ready to receive the image attachment, the user needs to choose a file from the system to upload. The user needs to add the fields, which include a file upload input field, in the existing form, like:

It is essential to use a file field for input and it must reference the image attribute (or the reference name). The user is required to add the image attribute in the corresponding controller in the permitted list of parameters to access it.

Displaying uploaded Images:

We have done all the stuff, After carrying out all the steps from making the database active to storing the image, it’s now time to upload the image. For that, the user has to add the below-mentioned code to the index page:

By following each step, the user can easily implement the use of Active Storage. There are several possibilities to explore. It is not limited to a single image, as the user can implement the same process for multiple images or videos or any type of static file (like PDFs or others).

Leave a comment: