Tutorial on how to use Active Storage on Rails 6.2

Facebook
Twitter
LinkedIn

Understanding Active Storage in Rails 6.2

Active storage is an inbuilt gem in Rails that developers widely use to handle file uploads. Combined with the encrypted credentials feature in the latest releases of Rails, active storage is a safe and easy method to upload, serve, and analyze files onto cloud-based storage services as well as local storage.

 

To start with, we need to install the active storage gem. This step is followed by declaring attachment associations, uploading attachments, processing attachments, and adding validations.

Scale performance. Not price. Try Engine Yard today and enjoy our great support and huge scaling potential for 14 days.
Deploy your app for free with Engine Yard.

Active storage gem Installation

With any new application, the first step to enable active storage is to install the gem. Run the below to install this migration to create the three basic tables automatically:

bin/rails active_storage:install

 

Run the migration by below:

bin/rails db:migrate. 

 

This creates the three tables for your application as active_storage_blobs, active_storage_variant_records, and active_storage_attachments. Out of these three, the active_storage_attachments is a polymorphic join table

 

  • The blobs table holds some straightforward details about the uploaded file like filename and content type. It also stores the encoded key that points towards the uploaded file in the active storage service.
  • The active_storage_attachments table is a polymorphic join table that holds references to a blob and a record. The polymorphic option is set to true in t.references:record,   null: false, polymorphic: true, index: false line when this table was created. This is set this way because the record_id column has details on what type of data it is holding. The identification is made clear with the help of a foreign key and a class name defined in the table.
  • Usually, active storage stores original copies, but it also lets the user accommodate modifications like resizing file size. The active_storage_variant_records table holds details about all these modified files.
You might also like:   Services, the Missing Element in Rails Applications: A Discussion with Riaz Virani

Functionalities of Active Storage

 

Active storage gem is used to attach, remove, serve, and analyze files. 

 

Attaching files: Files can be attached as a single file or multiple files. Use macros like ‘has_one_attached’ and ‘has_many_attached’ accordingly. 

 

Below are the sample codes to add attachments.

 

One attachment:

class User < ApplicationRecord

  has_one_attached :avatar

End

Many attachments:

class Message < ApplicationRecord

  has_many_attached :images

End

Active storage enables attaching files and data to record on storage services. If we expand the ‘has_one_attached’ declaration, we can see that there is an avatar_attachment and an avatar_blob to get through the avatar_attachment association. 

 

Third-party services are used to open, view, and operate the attached files from storage services. The content type of attachment decides the kind of service to be used. 

 

If the avatar_attachment is an image file attachment, here’s how you can upload an image to this model. 

 

<%= f.label :avatar %>

<%= f.file_field :avatar %>

 

In order to display the uploaded image, run:

<%= image_tag event.avatar %>

 

It is always advisable to add custom validations to the files uploaded since the Active storage feature does not include in-built validations. File type and the file size must be validated before the upload, to avoid errors and complications.

 

As discussed above, Rails allows modification of the uploaded files and stores the data in the variants table. For example, to process image files, the image_processing gem of Rails can be used.

 

Remember to encrypt your storage service credentials before uploading to the cloud. Encrypted credentials are a safe way to handle cloud-based storage services like Amazon S3. 

You might also like:   Sending iOS Push Notifications via APNs

 

Removing files: The attached files can also be removed from the records by using the purge command.

User.avatar.purge

Serving files: The uploaded files can be served by active storage. Two methods are used for this – the redirecting method and the proxying method. The redirect method uses the file’s blob URL to serve the file, and the proxying method will download data in files from the storage service.

 

As mentioned, active storage uses third-party software to enable file processing. You can download and install libvips or ImageMagick v8.6+ for image analysis and transformations, ffmpeg v3.4+ for video/audio analysis and video previews, and poppler or muPDF for PDF previews separately, as Rails will not install this software.

Major active storage updates in recent releases

In the recent releases of Rails, the active storage gem has seen notable updates. The major ones are as follows:

  • In ffmpeg, the user can configure all those parameters used for generating a video preview image under config.active_storage.video_preview_arguments.
  • No error is raised when the mime type is unrecognizable.
  • When an image previewer cannot generate a preview image, ActiveStorage::PreviewError is raised.
  • Even with no service selected, Blob creation will not crash.
  • Like MuPD previewer, Poppler PDF previewer also uses the original document’s crop box to display a preview image. 
  • Configure attachments for the service you want to store them in.
  • Use any URL, private or public, for blobs. The latest Rails update on active storage extends support for this feature and ensures the public URLs are permanent.  

 

Now that you have seen how to install the active storage gem, explore its functionalities, releases, updates, and uploading files, we hope that this blog helped you gain a better understanding of active storage in Rail 6.2.

Want more posts like this?

What you should do now:

Facebook
Twitter
LinkedIn

Easy Application Deployment to AWS

Focus on development, not on managing infrastructure

Deploying, running and managing your Ruby on Rails app is taking away precious resources? Engine Yard takes the operational overhead out of the equation, so you can keep innovating.

  • Fully-managed Ruby DevOps
  • Easy to use, Git Push deployment
  • Auto scaling, boost performance
  • Private, fully-configured Kubernetes cluster
  • Linear pricing that scales, no surprises
  • Decades of Ruby and AWS experience

14 day trial. No credit card required.

Sign Up for Engine Yard

14 day trial. No credit card required.

Book a Demo