What is Active Storage in Ruby on Rails?
In today's digital world, applications often need to manage files, such as images, videos, and documents. When building a web application using Ruby on Rails, we would want to have the ability to store and manage files easily. That's where Active Storage comes in. In this blog post, we will go over what Active Storage is, how it works, and how to use it in your Ruby on Rails application.
What is Active Storage?
Active Storage is a built-in tool provided by Ruby on Rails to handle file uploads and attachments. It allows you to manage files easily and efficiently by providing a simple way to upload, store, and manipulate files within your application.
Active Storage is built on top of various storage services, such as Amazon S3, Google Cloud Storage, and Microsoft Azure Storage. It can also work with local disk storage, which is useful during development or for small-scale applications. By using Active Storage, you can switch between different storage services without having to change your application code.
Setting up Active Storage
To start using Active Storage in your Ruby on Rails application, you need to install it first. If you are using Rails 5.2 or later, Active Storage comes pre-installed. If you are using an older version of Rails, you can add the activestorage
gem to your Gemfile and run bundle install
.
Once Active Storage is installed, you can run the following command to generate the necessary configuration files and database tables:
rails active_storage:install
This command will generate a migration file that creates two new tables: active_storage_blobs
and active_storage_attachments
. These tables will store the metadata and the associations between your application's models and the attached files. To create the tables, run:
rails db:migrate
Now you have Active Storage set up and ready to use in your application.
Configuring a storage service
Before you can start using Active Storage, you need to configure a storage service. As mentioned earlier, Active Storage supports various storage services, such as Amazon S3, Google Cloud Storage, and Microsoft Azure Storage. It also supports local disk storage.
To configure a storage service, open the config/storage.yml
file that was generated when you installed Active Storage. Here, you will see examples of different storage service configurations. Uncomment or add the configuration for the storage service you want to use.
For example, if you want to use local disk storage, your config/storage.yml
file should look like this:
# Use rails credentials:edit to set the AWS_SECRET_ACCESS_KEY.
# See the Rails Credentials guide for more info.
# https://guides.rubyonrails.org/security.html#custom-credentials
local:
service: Disk
root: <%= Rails.root.join("storage") %>
Next, you need to tell your application which storage service to use. In config/application.rb
, add the following line to the config
block:
config.active_storage.service = :local
Replace the :local
symbol with the name of the storage service you configured in storage.yml
.
Now your application is configured to use Active Storage with the chosen storage service.
Attaching files to your models
To attach a file to a model, you need to define an attachment relationship between the model and the file. You can do this using the has_one_attached
or has_many_attached
methods, depending on whether you want to attach a single file or multiple files to each record.
For example, let's say you have a User
model, and you want each user to have an avatar image. In your user.rb
file, add the following line:
has_one_attached :avatar
Now each user can have one attached avatar. To attach an avatar to a user, you can use the avatar.attach
method:
@user.avatar.attach(params[:avatar])
You can also use the create
or update
methods to attach a file when creating or updating a record:
User.create(name: 'John Doe', avatar: params[:avatar])
To display the attached avatar in a view, you can use the url_for
helper method:
<%= image_tag url_for(@user.avatar) if @user.avatar.attached? %>
If you want to allow users to upload multiple files, you can use the has_many_attached
method instead. For example, if you have a Post
model and you want each post to have multiple images, add the following line to your post.rb
file:
has_many_attached :images
You can then attach images to a post using the images.attach
method:
@post.images.attach(params[:images])
And display the attached images in a view using the url_for
method:
<% @post.images.each do |image| %>
<%= image_tag url_for(image) %>
<% end %>
Uploading files with forms
To allow users to upload files through a form, you can use the file_field
form helper method. This method generates an HTML file input field that users can use to select a file from their computer.
For example, to create a form for uploading an avatar for a user, you can do the following:
<%= form_with model: @user, local: true do |form| %>
<%= form.label :avatar %>
<%= form.file_field :avatar %>
<%= form.submit %>
<% end %>
If you want to allow users to upload multiple files, you can use the multiple: true
option:
<%= form_with model: @post, local: true do |form| %>
<%= form.label :images %>
<%= form.file_field :images, multiple: true %>
<%= form.submit %>
<% end %>
Manipulating attached files
Active Storage provides various methods for manipulating attached files, such as resizing images, extracting metadata, and generating previews for non-image files.
To manipulate an attached image, you can use the variant
method. This method allows you to apply various transformations to the image, such as resizing, cropping, and rotating.
For example, to create a thumbnail version of an attached image, you can do the following:
<%= image_tag url_for(@user.avatar.variant(resize: "100x100")) if @user.avatar.attached? %>
This code will generate a 100x100 pixel thumbnail of the user's avatar. The variant
method uses the ImageMagick library to perform the transformations, so you need to have it installed on your system.
To extract metadata from an attached file, such as the dimensions of an image or the duration of a video, you can use the metadata
method:
width, height = @user.avatar.metadata[:width], @user.avatar.metadata[:height]
For non-image files, you can use the preview
method to generate a preview image, such as a thumbnail of the first page of a PDF document or a still frame from a video:
<%= image_tag url_for(@document.preview(resize: "100x100")) if @document.previewable? %>
Conclusion
Active Storage is a powerful tool provided by Ruby on Rails that allows you to easily manage file uploads and attachments in your application. It supports various storage services, such as Amazon S3, Google Cloud Storage, and Microsoft Azure Storage, as well as local disk storage. By using Active Storage, you can store and manipulate files in your application without having to worry about the underlying storage service.
In this blog post, we covered the basics of setting up and using Active Storage in a Ruby on Rails application. We showed how to configure a storage service, attach files to your models, upload files with forms, and manipulate attached files. With this knowledge, you should be able to start using Active Storage in your own Rails applications and build powerful file management features for your users.