【发布时间】: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 中也不起作用。
<<运算符在类定义中不起作用并且Things不是类。 -
嗨@asceta - 我不确定你所说的 是什么意思
-
他指的是您在模型中的
<<错字。 -
啊谢谢,已修复
标签: ruby-on-rails activerecord