【问题标题】:Filter Active Record by relation but not the relation itself按关系过滤 Active Record,而不是关系本身
【发布时间】: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


    【解决方案1】:

    这就是includes 的魔力——因为您在其中使用bar,它决定使用左连接并且不会预加载任何其他内容。您必须在此处明确加入并预加载关联:

    Foo.joins(:bars).where(bars: {foobar: 2}).uniq.preload(:bars)
    

    前段时间我做了一个关于那些神奇方法的演讲,你可以在这里找到它:https://skillsmatter.com/skillscasts/6731-activerecord-vs-n-1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      相关资源
      最近更新 更多