【问题标题】:Rails: Child Record not Tracking Changes in ParentRails:子记录不跟踪父项的更改
【发布时间】:2010-12-15 21:29:45
【问题描述】:

我确定这是普通的 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 的新值。

这是怎么回事?

感谢您的洞察!

【问题讨论】:

    标签: ruby-on-rails activerecord associations model-associations


    【解决方案1】:

    这是由于 ActiveRecord 中缺少对象映射。在不修改父对象的情况下保存子对象不会刷新父对象。

    要刷新关联,请执行child.parent(true).name 之类的操作。

    【讨论】:

    • 内幕消息:Rails 3.1 可能会有一个object map。
    猜你喜欢
    • 2021-12-06
    • 1970-01-01
    • 2013-07-11
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多