Mặc dù accepts_nested_attributes_for(:foo, allow_destroy: true)
chỉ làm việc với các hiệp hội ActiveRecord như belongs_to
chúng ta có thể mượn từ thiết kế của nó để xóa tập tin đính kèm kẹp giấy theo cách tương tự.
(Để hiểu cách lồng các thuộc tính làm việc trong Rails thấy http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html).
Thêm một phương pháp <attachment_name>_attributes=
nhà văn như dưới đây để mô hình của bạn mà đã sử dụng has_attached_file
:
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
Phương pháp <attachment_name>_attributes=
gọi Paperclip::Attachment#clear
để đánh dấu đính kèm để hủy diệt khi mô hình được lưu tiếp theo.
Tiếp theo mởhiện tạifile (sử dụng đường dẫn tập tin chính xác cho ứng dụng của bạn) và thiết lập các thông số mạnh mẽ cho phép _destroy
cờ lồng thuộc tính trên <attachment_name>_attributes
:
ActiveAdmin.register YourModelHere do
permit_params :name, :subdomain,
:standalone_background,
standalone_background_attributes: [:_destroy]
Trong cùng một tập tin, thêm một _destroy
hộp lồng nhau để khối ActiveAdmin form
. Hộp kiểm này phải được lồng trong phạm vi <attachment_name>_attributes
bằng cách sử dụng semantic_fields_for
(hoặc một trong các phương thức thuộc tính lồng nhau khác do formtastic cung cấp).
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
Biểu mẫu của bạn giờ đây sẽ hiển thị hộp kiểm xóa khi có tệp đính kèm. Chọn hộp kiểm này và gửi biểu mẫu hợp lệ phải xóa tệp đính kèm.
Nguồn: https://github.com/activeadmin/activeadmin/wiki/Deleting-Paperclip-Attachments-with-ActiveAdmin
Bạn quên xóa tệp đính kèm với standalone_background.clear – kars7e