0

I have two models, both associated with each other through has_many through.

I can query the model and filter based on its associated records:

Car.includes(:equipment).where(equipment: { id: [1, 2, 3] })

The problem is that I want to require all of those records, rather than requiring just one of them.

Is there a way to build a query that requires all of the values in the array (the [1, 2, 3] from the above example).

In other words, I'd like to query for all cars that have all three equipment (ids of 1, 2 and 3).

1 Answer 1

1

Assuming you have an id_ary like [1,2,3], how about something like:

id_ary.each_with_object(Car.includes(:equipment)) do |id, scope|
  scope.where(equipment: {id: id})
end

Looping like that should and your where conditions, I believe.

Sign up to request clarification or add additional context in comments.

1 Comment

Works great! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.