从记录集合中获取has_many通过关系的所有记录

时间:2016-06-30 18:48:23

标签: ruby-on-rails activerecord

鉴于此模型:

ModelOne
  has_many: ModelTwo
  has_many: ModelThree through: ModelTwo

ModelTwo
  belongs_to: ModelOne
  has_many: ModelThree

ModelThree
  belongs_to: ModelTwo

我想获得属于ModelOnes集合的所有ModelThrees,例如:

ModelOne.where(<some condition>).model_threes

无需遍历所有ModelOnes

我发现搜索到的所有答案仅涵盖了has_many:来自单个记录

3 个答案:

答案 0 :(得分:1)

你可以试试这个......

ModelThree.joins(:model_ones).where(model_ones: { <some condition> })

更新尝试添加has_many:model_ones,通过:: model_twos添加到ModelThree

答案 1 :(得分:0)

我可能会偶然发现我的事情,但有点像:

ModelThree.joins(model_two: :model_ones).where(model_two: { model_ones: { YOUR-WHERE-CLAUSE } })

很快会尝试一些东西,然后我可能会更新!

<强>更新 更改了model_two

的复数形式

答案 2 :(得分:0)

我使用model_three.joins(model_two: :model_one).where(model_ones: {<the condition>})

进行了此操作
相关问题