Carrierwave多图片上传

7

我正在使用来自主分支和PostgreSQL的多文件上传。我的产品模型有一个名为“images”的字符串字段,我可以成功地附加多个图像。

不过我无法弄清如何从产品中删除一个图像。我可以按照文档中描述的方式删除所有图像:

product.remove_images!
product.save

但是我没有找到删除单个图像的方法。


1
你的属性名中有“images”或“image”吗? - Pavan
“从主分支进行多文件上传” - 除了carrierwave之外,是否还有其他的gem可以使用?或者你指的是什么? - amiuhle
请查看 https://github.com/carrierwaveuploader/carrierwave#multiple-file-uploads,注意:您必须指定使用主分支才能启用此功能。 - Cris
@Pavan 图像是属性: t.string "images",array: true - Cris
4个回答

3

您是否考虑使用嵌套表单来尝试删除图像?

以下是来自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 %>

为了使其正常工作,请确保在您的Gemfile中包含gem 'nested_form','〜> 0.3.2'
希望这可以帮助您。

只有一个属性,嵌套表单应该放在哪里?如果您阅读主分支上的自述文件:https://github.com/carrierwaveuploader/carrierwave#multiple-file-uploads 我有一个存储数组的单列。如果我有一个图片的单独模型,你的解决方案会起作用,但我没有。我开始查看carrierwave的mount_multiple_spec.rb,我开始思考是否有方法。 - Cris

1

我从 @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

我写了一篇博客文章关于这个话题,并创建了一个带有更具体代码的示例项目

0
将类似以下内容添加到产品模型即可解决问题。
  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还负责在保存记录之后删除文件。

0

你应该能够在指定的图像上使用remove_image(从数组中)。因此,你需要先以某种方式识别出这个图像(例如:images[0].remove_image!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接