It seems like adding an invalid belongs_to association to a model silently returns nil when that association is invoked.
In the example below, there is no bar_id column in the foos table. There’s not even a Bar model:
class Foo < ApplicationRecord
belongs_to :bar
end
Foo.last.bar
# => nil
This behavior persists even when explicitly specifying an invalid foreign_key to belongs_to.
I’m sure there’s a reason for this but it can be very confusing. It mislead me to believe I had missing database record when in fact I had just made a typo.
This is also not consistent with the behavior of has_one which will error if the association can’t be mapped back to an existing model.
Assuming it did once do the right thing, you could try to git bisect down to the change that broke it, using the standalone AR bug template to track it.
Alternatively, if you’d rather trace the current behaviour (or you’re not sure when / whether it previously worked), I’d expect something in this block of code to raise an exception. That’s certainly not an answer, but hopefully it gets you through enough of the outer layers of indirection, and you can explore from there.
Thanks for the pointers @matthewd, @Betsy_Haibel .
I’ve tried bisecting but it became a bit of a hassle to run the AR bug template on versions older than 5, but I was able to confirm that this behavior was already present on version 5.
I’ve created a more detailed issue on github with a proposed solution based on my fidings.