Remove assosiation instead of destroying object when :allow_destroy => true
-
18-09-2019 - |
Question
When using the new accepts_nested_attributes_for
in ActiveRecord, it's possible to use the option :allow_destroy => true
. When this option is set, any hash containing nested attributes like {"_delete"=>"1", "id"=>"..."}
passed to update_attributes
will delete the nested object.
Simple 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 deleting the nested objects when "_delete" => "1"
- just remove the association? (i.e. In the above case set the forum_id on the user to nil)
Bonus question: What if I also want to change the an attribute on the nested object when removing the association? (e.g. like setting a state or a timestamp)
Solution
Instead of asking for the user to be deleted using "_delete" => '1'
, can you not just update it using the nested_attributes?:
Forum.first.update_attributes("users_attributes"=> {
"0" => {
"id" => "42",
"forum_id" => "",
"state" => 'removed'
}
})