-
Notifications
You must be signed in to change notification settings - Fork 0
Deleting Paperclip Attachments with ActiveAdmin
This technique will be consistent with how Rails' built-in nested attributes for associations work once the magic and mystery is removed.
To delete an attachment. an Author
model with an avatar
attachment:
class Author < ApplicationRecord
...
has_attached_file :avatar
...
end
As accepts_nested_attributes_for
only works with ActiveRecord associations like has_one
, has_many
, etc. we will not make direct use of it, but manually add the writer method it generates itself.
(To understand how nested attributes work in Rails see http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html).
Add a <attachment_name>_attributes=
writer method like below to your model that already uses has_attached_file
:
class Author < ApplicationRecord
...
has_attached_file :avatar
+ def avatar_attributes=(attributes)
+ # Marks the attachment for destruction on next save,
# # if the attributes hash contains a _destroy flag:
+ avatar.clear if has_destroy_flag?(attributes)
+ end
end
The method calls Paperclip::Attachment#clear
to mark the attachment for destruction when the model is next saved.
Open app/admin/authors.rb
(use the correct file path for your app) and setup strong parameters to permit the _destroy
flag nested attribute:
# File: app/admin/authors.rb
ActiveAdmin.register Author do
- permit_params :name, :bio, :avatar
+ permit_params :name, :bio, :avatar, avatar_attributes: [:_destroy]