Rails Active Storage

Tram Ho

1. Introduction

If before Rails version 5.2, to upload files, most of us always need a 3rd party library, one of which is the most famous one is CarrierWave gem – it is a very stable gem and is believed by the community. use the most. But from Rails 5.2 onwards, we have another option is Active Storage . Unlike CarrierWave, Active Storage is built into Rails or in other words it is developed by Rails, so we are completely assured when using

2. Installation

Migration

Although Active Storage is built into Rails, by default it is not installed when running rails new. To install Active Storage we run the following command:

After running these two commands, it will create two tables in the DB named active_storage_blobs and active_storage_attachments . By default, Active Storage uses a Polymorphic relation in rails, active_storage_blobs contains file information, and active_storage_attachments is a polymorphic join table that stores the model’s class name.

Setting

We implement the Declaration of Active Storage services in config / storage.yml . For each service our application uses, provide the required name and configuration. The example below declares three services named local, test and amazon :

Let Active Storage know which service to use by setting Rails.application.config.active_storage.service corresponding to each environment because each environment will probably use a different service.
For example, to use the Disk service in a development environment, we will add the following to config / environment / development.rb :

Or using s3 in production , I set it at config / environments / production.rb :

3. Use

Active Storage allows us to attach one or more files to a record using the has_one_attached and has_many_attached macros, respectively.
To illustrate, we consider the following example, a user has only 1 avatar or a product has many images. To perform that example we need to create the User and Product models as follows:

has_one_attached

Inside User model:

Inside controller and view

Thus, we can create avatars for users without creating more avatar fields in users table or any other table. In addition, to attach an avatar to an existing user, we can use user.avatar.attach (params [: avatar]) or check if the user has been attached avatar by using user.avatar.attached?

has_many_attached

The product has many images:

Share the news now

Source : Viblo