2015-07-13 86 views
7

我使用的是从master分支和PostgreSQL上的多个文件上传 我的产品模型有一个名为“images”的字符串字段,我可以附加多张图片就好了。Carrierwave多图像上传

虽然我弄不清楚,我怎样才能从产品中删除一张图片? 我可以删除在该文档中描述的所有图片:

product.remove_images! 
product.save 

,但没有找到一种方法如何删除单个图像。

+1

你有'图像'或'图像'作为属性名称吗? – Pavan

+0

“从主分支上传多个文件” - 除了carrierwave之外还有一个gem,或者你是什么意思? – amiuhle

+0

检查https://github.com/carrierwaveuploader/carrierwave#multiple-file-uploads 它说:注意:您必须指定使用主分支启用此功能: – Cris

回答

0

您应该可以在指定图像上使用remove_image(来自阵列)。所以你需要以某种方式首先识别图像(例如:images[0].remove_image!

+0

不幸的是这不起作用:( – Cris

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 %> 

为了使这项工作确保包括gem 'nested_form', '~> 0.3.2'在你的Gemfile。

希望这可以帮助你。

+0

只有一个属性,嵌套表单应该用在哪里?如果你阅读master分支上的自述文件:https://github.com/carrierwaveuploader/carrierwave#多文件上传 我havea存储阵列单列。如果我对图像一个独立的模型,我不知道。 我开始看mount_multiple_spec 您的解决方案是可行的。rb来自carrierwave,我开始认为现在有办法。 – Cris

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还负责删除文件。

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 

我写了blog post这一点,并创建一个更具体的代码的sample project