Using ActiveStorage for File Uploads in Rails 6
Introduction
With the release of Rails 6, the team introduced a new feature called ActiveStorage that simplifies
file uploads and management in Rails applications. ActiveStorage provides a high-level abstraction for
uploading files, associating them with models, and handling file storage services like local disk storage
and cloud providers such as Amazon S3, Google Cloud Storage, etc.
Installation
To start using ActiveStorage in your Rails 6 application, you need to add the gem to your Gemfile and
run the bundle install command:
gem 'activestorage'
After installing the gem, you need to run the ActiveStorage installation generator by running the
following command in your terminal:
rails active_storage:install
The generator will create the necessary migrations, database tables, and configuration files to set up
ActiveStorage in your application.
File Uploads
Once ActiveStorage is set up, you can start uploading files to your models. To enable file uploads for a
specific model, you need to add the has_one_attached
or has_many_attached
method in the corresponding model file.
class User < ApplicationRecord
has_one_attached :avatar
end
This will allow users to associate an avatar image with their profile. The has_one_attached
method creates an association between the model and the uploaded file.
File Storage
By default, ActiveStorage uses the local disk storage for file uploads. However, you can configure it to
use cloud storage services like Amazon S3, Google Cloud Storage, etc. To configure the storage service,
you need to modify the storage.yml
file in the config folder of your Rails application.
# config/storage.yml
amazon:
service: S3
access_key_id:
secret_access_key:
region:
bucket:
The above configuration sets up the Amazon S3 storage service with the required access key, secret
access key, region, and bucket name. You can substitute these values with your own.
Displaying Uploaded Files
ActiveStorage provides convenient methods to display uploaded files in your views. You can use the
url
method to retrieve the public URL of an attached file. For example, to display a user’s
avatar image, you can use the following code in your view:
<%= image_tag @user.avatar.url if @user.avatar.attached? %>
The attached?
method checks if a file is attached to the user’s avatar attribute. If
attached, it displays the image using the image_tag
helper method.
Conclusion
ActiveStorage in Rails 6 provides a simple and powerful way to handle file uploads in your applications.
Whether you need to upload user avatars, product images, or any other type of files, ActiveStorage makes
the process seamless and efficient. Take advantage of the versatility and ease of use ActiveStorage offers
to enhance the user experience in your Rails projects.
Leave a Reply