Download multiple Carrierwave images

I use several file uploads from the main branch and PostgreSQL. My product model has a string field called "images" and I can attach several images just fine.

What I can’t understand, how can I remove one image from products? I can delete all images as described in the docs:

product.remove_images! product.save 

but did not find a way to delete a single image.

+7
ruby-on-rails carrierwave
source share
4 answers

Do you consider using a nested form to try to delete an image?

Here is a snippet of code from the github site support structure ...

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

... which I'm sure you saw. Although, of course, call remove_images! will not work in your case, as this implies a uniform action for all images.

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

 <%= 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, be sure to include gem 'nested_form', '~> 0.3.2' in your Gemfile.

Hope this helps you.

+3
source share

I learn @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 am creating a sample project with more specific codes.

+1
source share

You should be able to use remove_image on the specified image (from an array). Therefore, you need to somehow identify the image first (for example, images[0].remove_image! )

0
source share

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 deleting the file after saving the record.

0
source share

All Articles