Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 619
Cris Avatar asked Jul 13 '15 10:07

Cris


2 Answers

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.

like image 109
Timur Mamedov Avatar answered Sep 25 '22 22:09

Timur Mamedov


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.

like image 21
Bob Avatar answered Sep 22 '22 22:09

Bob