Although accepts_nested_attributes_for(:foo, allow_destroy: true)
only works with ActiveRecord associations such as belongs_to
, we can characterize its design to work similarly with removing attachments in paperclip.
(To understand how nested attributes work in Rails, see http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html).
Add a way to write <attachment_name>_attributes=
, as shown below, into your model that already has has_attached_file
:
has_attached_file :standalone_background def standalone_background_attributes=(attributes)
The <attachment_name>_attributes=
calls Paperclip::Attachment#clear
to mark the attachment to be destroyed when the next model is saved.
Then open the existing app/admin/your_model_here.rb
(use the correct file path for your application) and configure strong parameters so that the nested _destroy
flag in <attachment_name>_attributes
:
ActiveAdmin.register YourModelHere do permit_params :name, :subdomain, :standalone_background, standalone_background_attributes: [:_destroy]
In the same file, add the nested _destroy
block to the ActiveAdmin form
block. This flag must be nested in <attachment_name>_attributes
using semantic_fields_for
(or one of the other nested attribute methods provided by formtastic).
form :html => { :enctype => "multipart/form-data"} do |f| f.inputs "Details" do ... end f.inputs "General Customisation" do ... if f.object.standalone_background.present? f.semantic_fields_for :standalone_background_attributes do |fields| fields.input :_destroy, as: :boolean, label: 'Delete?' end end end end
Your form should now show the delete flag when there is an application. Checking this box and submitting the correct form should remove the attachment.
Source: https://github.com/activeadmin/activeadmin/wiki/Deleting-Paperclip-Attachments-with-ActiveAdmin