I’m sure this is ordinary Rails behavior, and I’m missing something fundamental, but what is it?
A child belongs to a parent, a parent has many members.
parent = Parent.create(:name=>"Kerkhoff, J")
child = parent.children.create(:first_name => "Sally")
puts child.parent.name # ==> Kerkhoff, J
parent.update_attributes(:name=>'Zorro, A')
puts parent.name # ==> 'Zorro, A'
puts child.parent.name # ==> 'Kerkhoff, J'
child.save # ==> true (Does saving the child refresh its parent.name?)
puts child.parent.name # ==> 'Kerkhoff, J' (No)
child = Child.find(child.id) # reload child from database
puts child.parent.name # ==> 'Zorro, A' (This does refresh the name)
Although the name attribute of parent has been changed, and though child continues to refer to the same parent, it does not reflect the parent’s updated attribute. It is not a matter of the update_attributes failing, either. If Sally’s record (child) is retrieved again from the database, the name attribute reflects parent‘s new value.
What is going on here?
Thanks for your insight!
This is due to a lack of an object map in ActiveRecord. Saving the child object without modifying the parent will not refresh the parent.
To refresh the association, do something like
child.parent(true).name.