Why is my simple self-referential association getting inverse_of wrong?

Viewed 112

I have a model like this:

class Thing < ApplicationRecord
  belongs_to :thing
  has_many :things
end

In rails 5 this was working. In rails 6.1, this happens:

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

the behavior is fixed by adding inverse_of:

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

Is this a bug or expected behavior?

1 Answers
Related