【问题标题】:Why is my simple self-referential association getting inverse_of wrong?为什么我的简单自引用关联会出现 inverse_of 错误?
【发布时间】:2021-10-14 10:38:29
【问题描述】:

我有一个这样的模型:

class Thing < ApplicationRecord
  belongs_to :thing
  has_many :things
end

在 Rails 5 中,这是有效的。在 Rails 6.1 中,会发生这种情况:

t1 = Thing.create
t2 = Thing.create(thing: t1)
t3 = Thing.create(thing: t2)

t3.thing.id # t2 id, correct
Thing.find(t3.thing_id).thing.id # t1 id, correct
t3.thing.thing.id # t3 id, incorrect! for some reason it loops back when loading this record

通过添加 inverse_of 来修复行为:

class Thing < ApplicationRecord
  belongs_to :thing, inverse_of: :things
  has_many :things, inverse_of: :thing
end

这是错误还是预期行为?

【问题讨论】:

  • 这在 Rails 5 中也不起作用。 &lt;&lt; 运算符在类定义中不起作用并且Things 不是类。
  • 嗨@asceta - 我不确定你所说的 是什么意思
  • 他指的是您在模型中的&lt;&lt; 错字。
  • 啊谢谢,已修复

标签: ruby-on-rails activerecord


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多