- 
                Notifications
    
You must be signed in to change notification settings  - Fork 2.3k
 
ActiveStorage
        Chip edited this page Aug 17, 2021 
        ·
        13 revisions
      
    Install and configure according to the official instruction, first.
Your model should look like this:
class Article < ActiveRecord::Base
  has_one_attached :asset
endYou can specify the field as an 'active_storage' type if not detected:
field :asset, :active_storageYou 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' }
endThe 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
endfield :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
endSupport for multiple uploads works the same way:
class Article < ActiveRecord::Base
  has_many_attached :assets
endclass 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
endfield :assets, :multiple_active_storage do
  delete_method :remove_assets
end#TODOShowing thumbnails may require additional setup.
For images, Rails 6 recommend installing the image_processing gem:
# add to your gemfile
gem 'image_processing', '~> 1.2'