-
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
end
You can specify the field as an 'active_storage' type if not detected:
field :asset, :active_storage
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
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
Support for multiple uploads works the same way:
class Article < ActiveRecord::Base
has_many_attached :assets
end
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
#TODO
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'