Remove association instead of destroying object when: allow_destroy => true
When using new accepts_nested_attributes_for
in ActiveRecord, the option can be used :allow_destroy => true
. When this option is set, any hash that contains nested attributes, such as {"_delete"=>"1", "id"=>"..."}
passed in update_attributes
, removes the nested object.
Easy setup:
class Forum < ActiveRecord::Base
has_many :users
accepts_nested_attributes_for :users, :allow_destroy => true
end
class User < ActiveRecord::Base
belongs_to :forum
end
Forum.first.update_attributes("users_attributes"=>{"0"=>{"_delete"=>"1", "id"=>"42"}})
Question: How do I - instead of removing nested objects, when "_delete" => "1"
- just remove the association? (i.e. in the above case, set the forum_id for the user to nil)
Bonus question: What if I also want to change the attribute for the nested object when removing the association? (for example, to set a state or timestamp)
Instead of asking the user to be deleted with a help "_delete" => '1'
, can you just update it with nested_attributes ?:
Forum.first.update_attributes("users_attributes"=> {
"0" => {
"id" => "42",
"forum_id" => "",
"state" => 'removed'
}
})