user1596316 user1596316 - 4 months ago 8
Ruby Question

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

Answer

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

Comments