6

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

I have a product edit page, where sub-categories of products are linked in product_sub_categories. To assign sub-categories to product, I used nested attributes for product_sub_categories. So, product can have more than one sub_categories.

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 product edit 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 %>

Code works well for adding sub-categories. But fails when I remove sub-category. Log 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)

Though, i click on Remove, it just passes _destroy="1", but doesn't destroy sub-category.

Can anybody tell the solution?

Update:

Extremely sorry for my stupid mistake. I didnt see code properly. In the model i duplicated

accepts_nested_attributes_for :product_sub_categories

without :allow_destroy => true. When i removed it, code worked properly.

Community
  • 1
  • 1
user2206724
  • 1,265
  • 3
  • 20
  • 38

1 Answers1

0

You need to add dependent destroy clause next to association, and it will destroy product's sub categories.

has_many   :product_sub_categories, :dependent => :destroy
Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
Muhammad Sannan Khalid
  • 3,127
  • 1
  • 22
  • 36