【发布时间】:2016-06-03 16:12:57
【问题描述】:
我想通过它的关系值过滤具有 has_many 关系的模型。
这很容易通过使用Foo.include(:bars).where(bars: { foobar: 2 }) 来实现。
如果我们的数据库中有这样的对象:
{
id: 1,
bars: [
{ id: 4, foobar: 1 },
{ id: 5, foobar: 2 }
]
}
这个查询只会返回这个:
{
id: 1,
bars: [
{ id: 5, foobar: 2 }
]
}
我仍想按此关系过滤我的记录,但接收该关系中的所有记录。
我可以通过使用类似Foo.include(:bars).joins('LEFT JOIN bars AS filtered_bars ON filtered_bars.foo_id = foos.id').where(filtered_bars: { foobar: 2 }) 的方式来实现这一点,但这看起来不太漂亮。
有没有更好的方法来做到这一点?
【问题讨论】:
标签: ruby-on-rails activerecord rails-activerecord