user1596316 user1596316 - 6 months ago 15
Ruby Question

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

Given this model:

has_many: ModelTwo
has_many: ModelThree through: ModelTwo

belongs_to: ModelOne
has_many: 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


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