Jarfis
Jarfis

Reputation: 125

Get all records in a has_many through relation from a collection of records

Given this model:

ModelOne
  has_many: ModelTwo
  has_many: ModelThree through: ModelTwo

ModelTwo
  belongs_to: ModelOne
  has_many: ModelThree

ModelThree
  belongs_to: ModelTwo

I would like to get all ModelThrees that belong to a collection of ModelOnes, like:

ModelOne.where(<some condition>).model_threes

without having to loop through all of the ModelOnes

all of the answers I've found searching for this only cover the has_many: through from a single record

Upvotes: 1

Views: 975

Answers (3)

Jarfis
Jarfis

Reputation: 125

I got this working using model_three.joins(model_two: :model_one).where(model_ones: {<the condition>})

Upvotes: 1

tpho
tpho

Reputation: 33

You could try this...

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

Update Try adding has_many :model_ones, through: :model_twos to ModelThree

Upvotes: 1

davidwessman
davidwessman

Reputation: 1228

I might stumble on my things here, but something like:

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

Gonna try something out soon and then I might update! 😄

Update Changed plural form of model_two

Upvotes: 1

Related Questions