views:

41

answers:

2

If I have

class Parent < ...
has_many :children,
         :before_add => :prepare_baby_room
         :after_remove => :plan_holiday
end

class Child < ...
belongs_to :parent
:after_create => :gurgle_a_lot
:after_remove => :cry
end

and I want to re-associate a child with a different parent, what's the cleanest way to do it whilst ensuring that all callbacks are called both on the parent side and on the child side?

i.e. i want t achieve something like this

@child = @curr_parent.children.first
@child.update_attributes(:parent_id, @new_parent)

do i just do something like

@child = @curr_parent.children.first
@curr_parent.children.delete(@child)
@new_parent.children.create(@child)
@child.update_attributes(:parent_id, @new_parent)
A: 

I haven't tried it, but I suspect you should just be able to reparent the child:

child = parent.children.first
child.parent = new_parent
child.save!
François Beausoleil
You can try this:child = oldParent.children.firstnewParent.children << child
KandadaBoggu
I think this suffers from the same probems as ive replied to KandadaBoggus reply
adam
A: 

This should work too:

child = oldParent.children.first
newParent.children << child
KandadaBoggu
that wont invoke the callbacks in the child class as the child hasnt been created. Also only the newParent before_add callback will be called. What about the oldParents after_remove?
adam