Rails: nested_form gem remove does not work, but add work

My problem is somewhat similar to the nested_form gem add works question , but remove the crash ... why? .

I have a product editing page where product subcategories are linked in product_sub_categories. To assign subcategories to the product, I used nested attributes for product_sub_categories. Thus, a product may have several subcategories.

In product model

has_many :product_sub_categories has_many :sub_categories, :through => :product_sub_categories accepts_nested_attributes_for :product_sub_categories, :allow_destroy => true 

And in the product editing view:

  <%= f.fields_for :product_sub_categories do |product_sub_category| %> <%= product_sub_category.collection_select :sub_category_id, @sub_categories, :id, :sub_category, {:include_blank => 'Select a Sub Category'} %> <%= product_sub_category.link_to_remove "Remove", :class => "subcatlink" %> <% end %> 

The code works well for adding subcategories. But crash when deleting a subcategory. The magazine gives:

  "product_sub_categories_attributes"=>{"0"=>{"sub_category_id"=>"1", "_destroy"=>"false", "id"=>"9"}, "1"=>{"sub_category_id"=>"1", "_destroy"=>"1", "id"=>"17"}}, ProductSubCategory Load (0.2ms)[0m [1mSELECT `product_sub_categories`.* FROM `product_sub_categories` WHERE `product_sub_categories`.`product_id` = 8 AND `product_sub_categories`.`id` IN (9, 17) 

Although, I click "Delete", it just skips _destroy = "1", but does not destroy the subcategory.

Can anyone tell a solution?

Update:

I am extremely sorry for my stupid mistake. I did not see the code correctly. In the model, I am duplicated

 accepts_nested_attributes_for :product_sub_categories 

without: allow_destroy => true. When I deleted it, the code worked correctly.

+6
source share
1 answer

You need to add the dependent destroy clause next to the association and destroy the product subcategories.

 has_many :product_sub_categories, :dependent => :destroy 
0
source

All Articles