虽然 accepts_nested_attributes_for(:foo, allow_destroy: true) 仅适用于像 belongs_to 这样的 ActiveRecord 关联,但我们可以借鉴其设计,以类似的方式进行回形针附件删除工作。
(要了解嵌套属性在 Rails 中的工作原理,请参阅 http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html).
向已经使用 has_attached_file 的模型添加如下所示的 <attachment_name>_attributes= 编写器方法:
has_attached_file :standalone_background
def standalone_background_attributes=(attributes)
# Marks the attachment for destruction on next save,
# if the attributes hash contains a _destroy flag
# and a new file was not uploaded at the same time:
if has_destroy_flag?(attributes) && !standalone_background.dirty?
standalone_background.clear
end
end
<attachment_name>_attributes= 方法调用Paperclip::Attachment#clear 标记附件,以便在下次保存模型时销毁。
接下来打开现有的app/admin/your_model_here.rb 文件(为您的应用使用正确的文件路径)并设置强参数以允许<attachment_name>_attributes 上的_destroy 标志嵌套属性:
ActiveAdmin.register YourModelHere do
permit_params :name, :subdomain,
:standalone_background,
standalone_background_attributes: [:_destroy]
在同一文件中,将嵌套的 _destroy 复选框添加到 ActiveAdmin form 块。此复选框必须使用 semantic_fields_for(或 formtastic 提供的其他嵌套属性方法之一)嵌套在 <attachment_name>_attributes 中。
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
当存在附件时,您的表单现在应该显示一个删除复选框。选中此复选框并提交有效的表单应该会删除附件。
来源:https://github.com/activeadmin/activeadmin/wiki/Deleting-Paperclip-Attachments-with-ActiveAdmin