我正在使用来自主分支和PostgreSQL的多文件上传。我的产品模型有一个名为“images”的字符串字段,我可以成功地附加多个图像。
不过我无法弄清如何从产品中删除一个图像。我可以按照文档中描述的方式删除所有图像:
product.remove_images!
product.save
但是我没有找到删除单个图像的方法。
我正在使用来自主分支和PostgreSQL的多文件上传。我的产品模型有一个名为“images”的字符串字段,我可以成功地附加多个图像。
不过我无法弄清如何从产品中删除一个图像。我可以按照文档中描述的方式删除所有图像:
product.remove_images!
product.save
但是我没有找到删除单个图像的方法。
您是否考虑使用嵌套表单来尝试删除图像?
以下是来自carrierwave的GitHub站点的一段代码...
<%= form_for @product, html: { multipart: true } do |f| %>
.
.
.
<label>
<%= f.check_box :remove_images %>
Remove images
</label>
<% end %>
...我相信你肯定见过。当然,调用remove_images!
并不能解决你的问题,因为这意味着对所有图像执行统一操作。
尝试使用上述修改,并查看是否可以帮助您解决此问题并分别针对每个图像进行操作...
<%= nested_form_for @product, :html=>{ :multipart => true } do |f| %>
.
.
.
<%= f.fields_for :images do |product_form| %>
<%= product_form.link_to_remove "Remove this image" %>
<% end %>
<% end %>
gem 'nested_form','〜> 0.3.2'
。我从 @Cris 那里学到了以下代码片段,用于处理 S3 相关工作。
def remove_image_at_index(index)
remain_images = @product.images # copy the array
deleted_image = remain_images.delete_at(index) # delete the target image
deleted_image.try(:remove!) # delete image from S3
@product.images = remain_images # re-assign back
end
def delete_image(idx)
remaining_images = []
self.images.each_with_index { |img,ii| remaining_images<<File.open(img.path) unless idx == ii}
self.images=remaining_images
end
你应该能够在指定的图像上使用remove_image
(从数组中)。因此,你需要先以某种方式识别出这个图像(例如:images[0].remove_image!
)