为什么我的简单的自我参照关联得到逆错误?



我有一个这样的模型:

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 bug:

  • https://github.com/rails/rails/issues/43478
  • https://github.com/rails/rails/pull/41552

最新更新