Active Storage helps you easily add file uploads to your Rails app. It manages storing files and linking them to your data.
0
0
File uploads with Active Storage in Ruby on Rails
Introduction
You want users to upload profile pictures.
You need to attach documents to records like invoices or reports.
You want to store images for blog posts or products.
You want to handle file uploads without writing complex code.
You want to serve uploaded files securely and efficiently.
Syntax
Ruby on Rails
class User < ApplicationRecord has_one_attached :avatar end # In a form view: <%= form_with model: @user do |form| %> <%= form.file_field :avatar %> <%= form.submit %> <% end %>
has_one_attached is for one file per record.
Use has_many_attached if you want multiple files.
Examples
This allows an article to have many images uploaded.
Ruby on Rails
class Article < ApplicationRecord
has_many_attached :images
endEnables direct uploads to cloud storage for faster uploads.
Ruby on Rails
<%= form.file_field :avatar, direct_upload: true %>
Attaches the uploaded file to the user record in the controller.
Ruby on Rails
user.avatar.attach(params[:user][:avatar])
Sample Program
This example shows a User model with one attached avatar file. The form lets users pick a file to upload. The controller saves the user and attaches the file.
Ruby on Rails
class User < ApplicationRecord has_one_attached :avatar end # Controller example class UsersController < ApplicationController def new @user = User.new end def create @user = User.new(user_params) if @user.save redirect_to @user, notice: "User created with avatar!" else render :new end end private def user_params params.require(:user).permit(:name, :avatar) end end # View (new.html.erb) <%= form_with model: @user, local: true do |form| %> <%= form.label :name %> <%= form.text_field :name %> <%= form.label :avatar %> <%= form.file_field :avatar %> <%= form.submit "Create User" %> <% end %>
OutputSuccess
Important Notes
Remember to run rails active_storage:install and migrate your database before using Active Storage.
Uploaded files are stored in a service like local disk, Amazon S3, or Google Cloud Storage configured in config/storage.yml.
Use rails server and check browser DevTools Network tab to see file upload requests.
Summary
Active Storage makes file uploads easy and secure in Rails.
Use has_one_attached or has_many_attached to link files to models.
Forms use file_field to let users pick files to upload.