Destroying An Object After Touching Its Relatives
Just a little thought I thought I should be sure to share, as it’s something I wasn’t aware of until this morning.
If you load an object in Rails and load any of it’s relatives through acts_as_tree, and then destroy the object, it will take the relatives with it.
@person = Person.find :first
@person.children.each do |child|
child.reassign_to_parent(x)
child.save
end
@person.destroy
The above code will destroy all of the children as well. My solution was to do a reload after I messed with the children.
@person = Person.find :first
@person.children.each do |child|
child.reassign_to_parent(x)
child.save
end
@person = Person.find @person.id
@person.destroy
This clears out the object’s knowledge of the children, and that destroy will leave the children alone.
