Handling file uploads is a common requirement for web applications, and Ruby on Rails makes this task straightforward with Active Storage.

Active Storage is a built-in library allows developers to attach files to models, handle uploads, and integrate with popular cloud storage providers like AWS S3, Google Cloud, or Azure.

Let's get started with file uploads in Rails using Active Storage.

What is Active Storage?

Active Storage is a Rails library introduced in Rails 5.2 which simplifies file uploads by providing a easy way to associate files with your database models.

With Active Storage, you can upload files to your local machine during development and switch to cloud services in production without changing much of your code.

Install Active Storage First

To start using Active Storage, follow these steps:

Install Required Gems

First make sure your Rails app includes the active_storage gem, which is part of Rails by default. If not, add it to your Gemfile and run bundle install.

ruby
gem 'activestorage'

Run Active Storage Migrations

Active Storage requires specific database tables to store metadata about the uploaded files. Generate and run the necessary migrations:

bash
rails active_storage:install
rails db:migrate

If you don't know what migration does, It creates tables like active_storage_blobs and active_storage_attachments in your database.

Configure Storage Service

Active Storage supports multiple storage services. Update config/storage.yml with your desired configurations. For local storage during development, the default setup works fine:

yaml
local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

In production, you can switch to cloud storage like AWS S3:

yaml
amazon:
  service: S3
  access_key_id: <%= ENV['AWS_ACCESS_KEY_ID'] %>
  secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %>
  region: us-east-1
  bucket: your-bucket-name

Add File Uploads to a Rails Model

To allow file uploads, add an attachment to your model. For example, if you have a User model and want to allow profile picture uploads:

ruby
class User < ApplicationRecord
  has_one_attached :profile_picture
end

For multiple file uploads, use has_many_attached instead:

ruby
class Post < ApplicationRecord
  has_many_attached :images
end

Build the File Upload Form

In your form views, use the file_field helper to add a file input. Rails automatically associates the uploaded file with the model.

erb
<%= form_with model: @user, local: true do |form| %>
  <%= form.label :profile_picture %>
  <%= form.file_field :profile_picture %>
  <%= form.submit "Upload" %>
<% end %>

For multiple uploads:

erb
<%= form_with model: @post, local: true do |form| %>
  <%= form.label :images %>
  <%= form.file_field :images, multiple: true %>
  <%= form.submit "Upload" %>
<% end %>

Display Uploaded Files

To display the uploaded file, use the url_for helper. Ensure you include the ActiveStorage::SetCurrent middleware in your application controller:

ruby
class ApplicationController < ActionController::Base
  include ActiveStorage::SetCurrent
end

Then, in your views:

erb
<%= image_tag url_for(@user.profile_picture) if @user.profile_picture.attached? %>

For multiple files:

erb
<% @post.images.each do |image| %>
  <%= image_tag url_for(image) %>
<% end %>

Validate and Processing Uploads

You can validate file types and sizes using gems like ActiveStorage::Validator. Add validations to your model:

ruby
class User < ApplicationRecord
  has_one_attached :profile_picture

  validates :profile_picture, content_type: ['image/png', 'image/jpg', 'image/jpeg'],
                               size: { less_than: 5.megabytes }
end

For image processing, use libraries like ImageMagick and gems like MiniMagick or Vips. Active Storage provides built-in support for transformations:

ruby
<%= image_tag @user.profile_picture.variant(resize: "100x100") %>

Hand Cloud Storage

Switching to a cloud provider is straightforward. Update your config/environments/production.rb to use the configured service:

ruby
config.active_storage.service = :amazon

Make sure to set your environment variables securely in production.

  • Configure CORS settings for your bucket to allow uploads from your domain.
  • Optimize file uploads with chunked uploads or background jobs.

Couple of Pros of Using Active Storage

Active Storage simplifies file handling in Rails, offering:

  • Seamless integration with your app's database.
  • Multi-cloud support with easy configuration.
  • Image processing and preview generation.
  • A clean API for attaching and accessing files.

Active Storage makes file uploads in Rails effortless. Whether you're building a portfolio site or a complex SaaS application, this tool helps you manage files efficiently. Start experimenting with Active Storage today and enhance your app's functionality with minimal effort!

For detailed documentation, visit the Rails Guides on Active Storage.

Did you learn something? If so then please share the feedback in comments below. Thanks


Comments(0)