【问题标题】:Carrierwave multiple image uploadCarrierwave 多张图片上传
【发布时间】:2015-12-30 20:01:18
【问题描述】:

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

但我无法弄清楚,如何从产品中删除一张图片? 我可以删除文档中描述的所有图像:

product.remove_images!
product.save

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

【问题讨论】:

  • 您有imagesimage 作为属性名称吗?
  • “从主分支上传多个文件” - 除了carrierwave之外还有gem,或者你的意思是什么?
  • 检查github.com/carrierwaveuploader/…,它说:注意:您必须指定使用主分支来启用此功能:
  • @Pavan images 是属性:t.string "images", array: true

标签: ruby-on-rails carrierwave


【解决方案1】:

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

这是来自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', '~&gt; 0.3.2'

希望这对您有所帮助。

【讨论】:

  • 属性只有一个,嵌套表格应该用在哪里?如果您阅读主分支上的自述文件:github.com/carrierwaveuploader/… 我有一个存储数组的列。如果我有一个单独的图像模型,你的解决方案会起作用,而我没有。我开始从carrierwave 中查看mount_multiple_spec.rb,我开始认为现在有办法。
【解决方案2】:

我向@Cris 学习,并在使用 S3 时使用以下代码 sn-p。

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

我为此写了一个blog post,并用更具体的代码创建了一个sample project

【讨论】:

    【解决方案3】:

    您应该能够在指定的图像(来自数组)上使用remove_image。所以你需要先以某种方式识别图像(例如images[0].remove_image!

    【讨论】:

      【解决方案4】:

      在产品模型中添加这样的东西就可以了。

        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 还负责在保存记录后删除文件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-02
        • 2015-05-17
        • 1970-01-01
        • 1970-01-01
        • 2018-02-12
        • 1970-01-01
        • 2018-06-19
        相关资源
        最近更新 更多