Rails:子记录不跟踪父记录的更改
我确信这是普通的 Rails 行为,并且我缺少一些基本的东西,但它是什么?
孩子属于父母,父母有许多成员。
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)
尽管 parent
的 name
属性已更改,并且 child
继续引用同一个父级,但它并不反映父级更新后的属性。这也不是 update_attributes 失败的问题。如果再次从数据库中检索 Sally 的记录 (child
),则 name
属性将反映 parent
的新值。
这是怎么回事?
感谢您的见解!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是由于 ActiveRecord 中缺少对象映射造成的。保存子对象而不修改父对象将不会刷新父对象。
要刷新关联,请执行
child.parent(true).name
之类的操作。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
.