尝试在下一个范围内包含所需的 Foo
Foo.includes(:bar).where("bars.col = x OR bars.id IS NULL")
或者
Foo.includes(:bar).where("bars.col = x AND bars.id IS NULL")
取决于你的需要
所以你可以动态地做,比如
#Foo class
def self.including_bars_equal_to(x) # or scope :including_bars_equal_to, :lambda{|x| ....}
self.includes(:bar).where("bars.col = ? AND bars.id IS NULL", x)
end
Attempt2
也许你应该尝试自定义加入和包含
Foo.joins("LEFT OUTER JOIN bars ON foos.id = bars.foo_id AND bars.col = 'x'").
includes(:bar)
或者您可以将连接与选择选择相结合
Foo.joins("LEFT OUTER JOIN bars ON foos.id = bars.foo_id AND bars.col = 'x'").
select("foos.*, bar.id as bar_id, bar.col as bar_col")