Rails 3, paper clip (& formtastic) - removal of attached images

I cannot find an example complete for all components. It’s hard for me to remove attached images.

  • Classes

    class Product has_many :product_images, :dependent => :destroy accepts_nested_attributes_for :product_images end class ProductImage belongs_to :product has_attached_file :image #(etc) end 
  • View

      <%= semantic_form_for [:admin, @product], :html => {:multipart => true} do |f| %> <%= f.inputs "Images" do %> <%= f.semantic_fields_for :product_images do |product_image| %> <% unless product_image.object.new_record? %> <%= product_image.input :_destroy, :as => :boolean, :label => image_tag(product_image.object.image.url(:thumb)) %> <% else %> <%= product_image.input :image, :as => :file, :name => "Add Image" %> <% end %> <% end %> <% end %> <% end %> 
  • controller

      class Admin::ProductsController < AdminsController def edit @product = Product.find_by_permalink(params[:id]) 3.times {@product.product_images.build} # added this to create add slots end def update @product = Product.find_by_permalink(params[:id]) if @product.update_attributes(params[:product]) flash[:notice] = "Successfully updated product." redirect_to [:admin, @product] else flash[:error] = @product.errors.full_messages render :action => 'edit' end end end 

It looks good, but literally nothing happens when I check the box. In the request, I see:

  "product"=>{"manufacturer_id"=>"2", "size"=>"", "cost"=>"5995.0", "product_images_attributes"=>{"0"=>{"id"=>"2", "_destroy"=>"1"}} 

But nothing is updated, and the product image is not saved.

Am I missing something fundamental in how accepts_nested_attributes_for works?

+5
ruby-on-rails ruby-on-rails-3 paperclip formtastic
Jan 15 '11 at 13:15
source share
1 answer

In API docs for ActiveRecord :: NestedAttributes :: ClassMethods

: allow_destroy

If true, destroys any elements from the attribute hash with the _destroy key and a value that evaluates to true (for example, 1, 1, true, or true). By default, this option is disabled.

So:

 accepts_nested_attributes_for :product_images, allow_destroy: true 
+10
Jan 15 2018-11-11T00:
source share



All Articles