Ruby on Rails Q & A

 

How to use ActiveStorage in Rails?

ActiveStorage is an integrated solution in Rails for uploading and attaching files, such as images and documents, to Active Record models. It streamlines file storage, supports multiple storage services (like Amazon S3, Google Cloud Storage, and Microsoft Azure Storage), and includes transformations via built-in image processing.

 

  1. Setup: First, to use ActiveStorage, you’ll need to run: `rails active_storage:install`. This generates a migration to add necessary tables. Then, run `rails db:migrate` to create those tables.

 

  1. Model Attachment: You can attach a file to a model by using `has_one_attached` for a single file or `has_many_attached` for multiple files. For instance, in a `User` model, if you want to attach a profile picture, you’d use: `has_one_attached :profile_picture`.

 

  1. Form Integration: To allow file uploads, use a file field in your forms. With the `form_with` helper, it could look like: `<%= form.file_field :profile_picture %>`.

 

  1. Storage Configuration: By default, ActiveStorage uses local storage. However, in a production environment, you’d typically use cloud services. This configuration is done in `config/storage.yml`. For example, to set up Amazon S3, you’ll specify service details (access keys, region, bucket, etc.) in this file.

 

  1. File Upload: Once a file is attached to a model, it’s uploaded to the specified storage service. You can then reference it in your views or controllers with methods like `user.profile_picture`.

 

  1. Variants: ActiveStorage supports on-the-fly transformations through variants. For instance, to display a resized image in a view, you can use: `<%= image_tag user.profile_picture.variant(resize: “100×100”) %>`. Variants require the `image_processing` gem and a processing backend like `MiniMagick`.

 

  1. Direct Uploads: To improve user experience, ActiveStorage supports direct uploads to a service like S3, bypassing your Rails app for enhanced speed and reduced server load. This requires some additional frontend JavaScript integration.

 

  1. Purging and Cleanup: To remove an attachment, you can use `user.profile_picture.purge`. Periodically, you might also want to clean up orphaned files using `rails active_storage:cleanup`.

 

ActiveStorage in Rails provides a comprehensive and convention-based approach to handling file uploads and attachments, making it straightforward for developers to manage various file storage tasks without relying on multiple external libraries.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Senior Software Engineer with a focus on remote work. Proficient in Ruby on Rails. Expertise spans y6ears in Ruby on Rails development, contributing to B2C financial solutions and data engineering.