-
Notifications
You must be signed in to change notification settings - Fork 2.3k
ActiveStorage
Shu Fujita edited this page Dec 4, 2019
·
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 a '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 upload works the same way:
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