(Workaround given at the end, but better suggestions appreciated)
I have a models Parent and Child, an the following association:
Parent
has_many :children, dependent: :destroy
Child
belongs_to :parent
Further, I have two Parent instances:
pfrom = Parent.find_by_id(from_id)
pto = Parent.find_by_id(to_id)
My goal is to transfer all children from pto to pfrom, and then delete
pto.
The first part seems to be easy:
pfrom.children.each { |ch| ch.update_attributes!(parent_id: pto.id }
If I run only this code, I can see that pto indeed contains now the
children formerly belonging to pfrom, and iterating over pfrom shows
that there are no children.
HOWEVER, if I add the following line:
pfrom.destroy
I can see (from the SQL statements which are issued by this call), that
all the former pfrom children are deleted!
It somehow seems as if this information has been “cached”. Could this be
the case? How then would I correctly implement the “move”.
====================================
WORKAROUND:
I found that if I destroy pfrom like this:
Parent.find_by_id(pfrom.id).destroy
only the dictionary is deleted. Hence, the pfrom variable still
remembered their children (even though pfrom.children.count had returned
zero).