Quick Summary:
Rails Active Storage is a framework for handling file uploads, analysis, and storing databases. This tutorial guide will help you understand how to upload files in Ruby on Rails using Active Storage step-by-step.
Table of Contents
Introduction
File uploads are crucial for web applications, but handling them can be messy. Well! You can avoid this mess. Rails Active Storage simplifies the process, providing a unified solution for uploading, storing, and analyzing files.
In this comprehensive guide, we will delve into the world of file uploads in Ruby on Rails, exploring the capabilities of Active Storage and providing step-by-step instructions to help you seamlessly integrate and manage file uploads in your Rails applications. First, let’s explore the history of file upload in Rails to understand better why Active Storage is implemented.
History of File Upload in Ruby on Rails
Rails 2.x Era (2007-2010)
- In the early days of Ruby on Rails, file uploads were handled using plugins like Paperclip and attachment_fu.
- Developers had to rely on third-party libraries to manage file attachments, and these solutions provided a basic set of features for uploading and storing files.
CarrierWave Integration (2011)
- CarrierWave, a flexible file upload library, gained popularity within the Rails community.
- In 2011, integrating CarrierWave into Rails applications became a common practice, offering more advanced features for image processing, Storage backends, and customization.
Rails 5.2: Introduction of Active Storage (2018)
- With the release of Rails 5.2 in April 2018, the framework introduced Active Storage as a built-in solution for file uploads.
- Active Storage simplified the process of handling file uploads by providing a standardized interface for integrating with different Storage services, including local disk storage, Amazon S3, and Google Cloud Storage.
Direct Uploads and DigitalOcean Spaces Support (2019)
- Rails 6, released in 2019, introduced direct uploads as a feature of Active Storage.
- Direct uploads allow clients to upload files directly to cloud Storage, improving performance and reducing server load.
- Rails 6 also supported DigitalOcean Spaces as a Storage service option, expanding the range of choices available for developers.
Rails 6.1: Resumable File Uploads (2020)
- Rails 6.1, released in December 2020, brought support for resumable file uploads.
- Resumable uploads enhanced user experience with the ability to resume interrupted uploads, especially beneficial for large files and unstable connections.
What is Active Storage?
Active Storage is a built-in Rails feature that empowers your applications to handle uploads effortlessly. It simplifies integration and management of single or multiple file uploads from your local machine, storing them locally or using external cloud storage services. You can retrieve various file types like images, videos, PDFs, and documents with ease.
By executing ActiveStorage in Ruby on Rails, adding a file field to each model is unnecessary. In simple words, the Rails Active Storage System is a robust and flexible way to handle file uploads and attachments. Active Storage also provides features such as image resizing, direct uploads, and file verifications.
You can also avoid bloating your file, which reduces website speed and performance. However, Active Storage in RoR applications stores your data files separately from the database, making it scalable and easier.
Moreover, Activesotrage uploads files on cloud Storage services like Google Cloud Storage, AWS S3, and Microsoft Azure. With Rails Active Storage, you do not need to worry about running out of space as you can store large amounts of information and attach those files to Active Record objects. As a result, it comes with a local disk-based service for development and testing.
Benefits of Active Storage in Ruby on Rails
✅ Flexibility: Supports cloud storage systems for versatile configuration and storage options.
✅ Integrated with Active Record: Makes associating and managing data streamlined through file attachments to models.
✅ Optimization: Offers a safe and efficient way to upload, serve, and analyze files on cloud storage.
✅ Automate handling: Resizes, adjusts file types, and automates scheduled expiration or deletion of uploaded files.
What are the requirements to upload file in Ruby on Rails Active Storage?
Various features of Active Storage depend on third-party software, which Rails will not install. They must be installed separately:
- libvips v8.6+ or ImageMagick for image analysis and transformations
- ffmpeg v3.4+ for video previews and ffprobe for video or audio analysis
- poppler or muPDF for PDF previews
For image analysis and transformations, uncomment the image_processing gem in your Gemfile, if necessary.
gem "image_processing", ">= 1.2"
Step-by-Step Guide to Setting Up Active Storage Rails
1. Install and Run Migrations
If creating a new Rails project, Active Storage is already included. Just install it and run migrations.
bin/rails active_storage:install
bin/rails db:migrate
This will create three new tables: active_storage_blobs, active_storage_attachments, and active_storage_variant_records.
Table Name |
Purpose |
Active_storage_blobs |
Stores information about uploaded files like filename and content type. |
Active_storage_attachments |
The polymorphic table connects your model to blobs If your model’s class name changes, you will need to operate a migration on this table to update the underlying record_type to your model’s new class name. |
Active_storage_variant_records |
If there is a different variant of the images, then it will be stored in this table. |
Then you need to declare services in config/service.yml. For each service your application uses, provide a name and the requisite configuration. The example below declares three services named local, test, and amazon:
local:
service: Disk
root: <%= Rails.root.join("storage") %>
test:
service: Disk
root: <%= Rails.root.join("tmp/storage") %>
amazon:
service: S3
access_key_id: ""
secret_access_key: ""
bucket: ""
region: "" # e.g. 'us-east-1'
3. Set Storage Service Per Environment
Then you need to define which service you need to use in which environment like in development.rb file config.active_storage.service = :local or in production.rb file config.active_storage.service = :amazon.
How to Use Active Storage with Rails model?
Let’s understand how to use Active Storage using Rails with an example.
1. Associate Attachment
For instance, we have a User model, and we want to store a profile image for a particular user. To store one image for a particular user, you can use the has_one_attached method.
class User < ApplicationRecord
has_one_attached :profile_image
end
2. Attaching Files
If you are generating a new model, then you can use the attachment type for the field.
rails g model User first_name:string last_name:string profile_image:attachment
This sets up a one-to-one association between the User model and an uploaded file named profile_image. If you are using the Rails form, then you can use file_field helper.
<%= form_with(model: @user, local: true) do |form| %>
<%= form.file_field :profile_image %>
<%= form.submit %>
<% end %>
- Permit Image in Strong Params
If you use API, you can send image data in the profile_image key.
def user_params
params.require(:user).permit(:name, :email, :avatar)
end
- How to Attach File Manually
So when we are uploading profile_image, it will be attached to the @user object. If you want to attach a manual file to an object, you can use the attach method.
user.profile_image.attach(params[:profile_image])
If you want to check that the attachment is attached or not a particular object, then you can use attached? Method.
user.profile_image.attached?
You can also add validations to your attachment.
validates :profile_image, content_type: ['image/png', 'image/jpg', 'image/jpeg'], size: { less_than: 5.megabytes }
3. Attaching Multiple Files
You can also attach multiple active Storage objects(images) to the object. Let’s say we have a post model and multiple images for the post. So we can use the has_many_attached method.
class Post < ApplicationRecord
has_many_attached :images
end
The only change we need to make is that we need to permit images as array in strong params, and it should be at least in the permit method.
def post_params
params.require(:post).permit(:title, :body, images:[])
end
4. Removing Files From Rails Active Storage
To remove attachments, you can use the purge or purge_later method. The purge will delete synchronously, and purge_later will do asynchronously, using the job. You don’t need to create any job for that active Storage to handle it.
# Synchronously destroy the avatar and actual resource files.
user.profile_image.purge
# Destroy the associated models and actual resource files async, via Active Job.
user.profile_image.purge_later
5. Generate URLs
You can use url_for, and rails_blob_path methods to generate URLs for attachments.
url_for(user.profile_image)
# => https://www.example.com/rails/active_storage/blobs/redirect/:signed_id/my-avatar.png
rails_blob_path(user.profile_image, disposition: "attachment")
Conclusion
This tutorial indicates file upload in Ruby on Rails using Active Storage. You can install, configure, and utilize the Rails Active Storage System for file attachments and uploads by following particular methods. Moreover, implementing Active Storage Ruby on Rails makes your file uploading work easier and lets you focus on developing the core functionality of applications.
If you need assistance or an expert solution, you can hire Ruby on Rails developer who helps you to upload files in Ruby on Rails using Active Storage and streamline the development process.
Frequently Asked Questions (FAQs)
Rails ActiveStorage supports numerous files like images, videos, PDFs, documents, and audio. However, the type will vary based on your Storage service capabilities.
Active Storage supports transformations using tools like ImageMagick or MiniMagick. You can crop, resize, or conduct other modifications on uploaded images.
You can solve issues with Active Job logs, which usually provide insights into background processing issues. Moreover, use debugging tools or logging libraries to pinpoint the source of the problem.
Yes, you can integrate features like drag-and-drop uploads, display previews, and progress bar to improve user experience.
You can use it by installing Active storage with rails active_storage: install and run migration. Also, another alternative is to add attachment has_one_attached:file and configuration storage.