Cris
Cris

Reputation: 951

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.

Upvotes: 7

Views: 1776

Answers (4)

Bob
Bob

Reputation: 2303

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.

Upvotes: 1

Cris
Cris

Reputation: 951

adding something like this to the product model does the trick.

  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 also takes care of removing the file after saving the record.

Upvotes: 0

Tim
Tim

Reputation: 1356

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.

Upvotes: 3

Cezar Halmagean
Cezar Halmagean

Reputation: 26

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!)

Upvotes: 0

Related Questions