Skip to content
Chip edited this page Aug 17, 2021 · 13 revisions

Install and configure according to the official instruction, first.

Your model should look like this:

Simple upload

class Article < ActiveRecord::Base
  has_one_attached :asset
end

You can specify the field as an 'active_storage' type if not detected:

field :asset, :active_storage

Deleting an attachment

You need to define a delete method if you want to delete attachment:

class Article < ActiveRecord::Base
  has_one_attached :asset
  attr_accessor :remove_asset
  after_save { asset.purge if remove_asset == '1' }
end

The method name is remove_#{name} by default, but you can configure it using delete_method option:

field :asset, :active_storage do
  delete_method :remove_asset
end

show correct file name of attachment

field :asset, :active_storage do
  delete_method :remove_asset
  pretty_value do
    if value
      path = Rails.application.routes.url_helpers.rails_blob_path(value, only_path: true)
      bindings[:view].content_tag(:a, value.filename, href: path)
    end
  end
end

Multiple uploads

Support for multiple uploads works the same way:

class Article < ActiveRecord::Base
  has_many_attached :assets
end

Deleting Multiple attachments

class Article < ActiveRecord::Base
  has_many_attached :assets
  # for deletion
  attr_accessor :remove_assets
  after_save do
    Array(remove_assets).each { |id| assets.find_by_id(id).try(:purge) }
  end
end
field :assets, :multiple_active_storage do
  delete_method :remove_assets
end

show correct file name for Multiple attachments

#TODO

show thumbnails on show and edit views

Showing thumbnails may require additional setup.

For images, Rails 6 recommend installing the image_processing gem:

# add to your gemfile
gem 'image_processing', '~> 1.2'
Clone this wiki locally