Carrierwave multiple image upload

I'm using multiple file uploads from the master branch and PostgreSQL My product model hast a string field called "images" and I can attach multiple images just fine.

What I can't figure out though, how can I remove one image from the products? I can remove all images as described in the docs:

product.remove_images!
product.save

but didn't find a way how to remove a single image.


Have you considered using a nested form for to try to delete an image?

Here is a piece of code from carrierwave's github site...

<%= form_for @product, html: { multipart: true } do |f| %>
  .
  .
  .
    <label>
      <%= f.check_box :remove_images %>
      Remove images
    </label>
<% end %>

...which I am sure you have seen. Although, of course, calling remove_images! would not work in your case, since that implies a unified action on all images.

Try the following modification of the above and see if it helps you sort this problem and target each image individually...

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

To make this work make sure to include gem 'nested_form', '~> 0.3.2' in your Gemfile.

Hopefully this helps you out.


I learn from @Cris and use the following code snippet when working with 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

I wrote a blog post about this , and create a sample project with more concrete codes.


You should be able to use remove_image on the specified image (from the array). So you'll need to somehow identify the image first (ex. images[0].remove_image! )

链接地址: http://www.djcxy.com/p/86678.html

上一篇: Java Hashmap:如何从价值中获取密钥?

下一篇: Carrierwave多图片上传