ActiveStorage for file uploads and attachments

Sarah Mitchell Feb 2026
2 tabs
# Installation
# rails active_storage:install
# rails db:migrate

# config/storage.yml
local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

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

google:
  service: GCS
  project: my-project
  credentials: <%= Rails.root.join("config/gcs.keyfile") %>
  bucket: my-app-bucket

# config/environments/production.rb
config.active_storage.service = :amazon

# Model with attachments
class User < ApplicationRecord
  has_one_attached :avatar
  has_many_attached :documents

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

class Post < ApplicationRecord
  has_one_attached :featured_image
  has_many_attached :gallery_images

  # Validation using custom validator
  validates :featured_image, attached: true,
            content_type: /Aimage/.*z/,
            size: { less_than: 10.megabytes }
end

# Attaching files
user = User.create!(name: 'John')

# From file upload
user.avatar.attach(params[:avatar])

# From file path
user.avatar.attach(
  io: File.open('/path/to/avatar.jpg'),
  filename: 'avatar.jpg',
  content_type: 'image/jpeg'
)

# Multiple files
post.gallery_images.attach(params[:images])

# Accessing attachments
user.avatar.attached?  # => true
user.avatar.filename   # => "avatar.jpg"
user.avatar.byte_size  # => 123456
user.avatar.content_type  # => "image/jpeg"

# URL for download
url_for(user.avatar)

# Removing attachments
user.avatar.purge       # Remove file synchronously
user.avatar.purge_later # Remove file via background job
2 files · ruby Explain with highlit

ActiveStorage handles file uploads with cloud storage integration. It supports local disk, S3, Google Cloud Storage, Azure. Files attach to models via has_one_attached and has_many_attached. I use ActiveStorage for avatars, documents, images. Image variants create on-demand thumbnails—crop, resize, format conversion. Direct uploads send files straight to cloud storage, reducing server load. Previews generate thumbnails for videos and PDFs. ActiveStorage integrates with Active Job for async processing. Testing uses fixture files and attachment stubs. Understanding blob storage vs. attachments vs. variants is key. ActiveStorage simplifies file handling compared to CarrierWave/Paperclip.