Table structure:
Bar:
a_id
b_id
attr1
attr2
...
Foo:
id
a_id
b_id
...
Models:
class Bar < ApplicationRecord
end
class Foo < ApplicationRecord
belongs_to :bar, lambda { |foo|
unscope(:where).where(
a_id: foo.a_id,
b_id: foo.b_id
)
}
def bar_working
Bar.find_by(
a_id: a_id,
b_id: b_id
)
end
end
Calling Foo.find(1).bar
yields nil. Calling Foo.find(1).bar_working
yields the associated object. Why is the scope not executed when I call the belongs_to association?
This works perfectly fine on a has_many association, just can't get it to work on the belongs_to.
I am running Rails 5.2.2.
Sources: