我正在尝试删除为模型上传的每个单个图像(工作有很多图像)但是现在我的代码工作方式如下:我在工作中上传了三个图像,我想删除一个但是当我检查时图像的复选框并提交更新操作,它将删除所有三个图像。
这是我的工作模型的代码:
before_save :destroy_image?
belongs_to :category
has_many :images, :as => :assetable, :class_name => "Work::Image", :dependent => :destroy
accepts_nested_attributes_for :images, :reject_if => proc { |attributes| attributes['attachment'].blank? }
def image_delete
@image_delete ||= "0"
end
def image_delete=(value)
@image_delete = value
end
private
def destroy_image?
self.images.clear if @image_delete == "1"
end
end
class Work::Image < Asset
has_attached_file :attachment, :styles => {:small => "200x150>", :large => "400x300>"},
:url => "/uploads/works/:id/:style/:basename.:extension",
:path => ":rails_root/public/uploads/works/:id/:style/:basename.:extension"
end
我认为问题在于删除所有图片
self.images.clear if @image_delete == "1"
但我不明白如何解决它。我希望在你的帮助下。
答案 0 :(得分:1)
您应该使用accepts_nested_attributes_for
的:allow_destroy
选项代替。
在你的形式上是这样的:
<% @work.images.each do |image| %>
<%= f.fields_for :images, image do |image_fields| %>
<%= image_tag image.url(:small) %>
<%= image_fields.check_box :_destroy %>
<% end %>
<% end %>