[英]Carrierwave multiple image upload
我正在使用来自主分支的多个文件上传和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'
包含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
您应该能够在指定的图像上使用remove_image
(来自数组)。 所以你需要先以某种方式识别图像(例如images[0].remove_image!
)
在产品模型中添加这样的东西就可以了。
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
保存记录后,Carrierwave还负责删除文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.