Ruby Activerecord IN clause
Asked Answered
U

2

82

I was wondering if anyone knew how to do an "IN" clause in activerecord. Unfortunately, the "IN" clause is pretty much un-googleable so I have to post here. Basically I want to answer a question like this "Give me all the college students that are in these dormitories where the dormitory id is in this array [id array]". I know how to write the query given a single dormitory id, but I don't know how to do it given an array of ids.

Any help is greatly appreciated. I'm sure this is a repost of a question somewhere, so I'll delete this once an answer/better search term is found.

Udall answered 16/4, 2012 at 21:18 Comment(1)
On the contrary: This page was the top result on a Google search for "activerecord in". ;-)Dislike
S
162

From §3.3.3 Subset Conditions of the Rails Guides:

If you want to find records using the IN expression you can pass an array to the conditions hash:

Customer.where(orders_count: [1,3,5])

This code will generate SQL like this:

SELECT * FROM customers WHERE
(customers.orders_count IN (1,3,5))

You can also use the arel syntax:

Client.where(Client.arel_table[:order_count].in([1,3,5]))

will generate the same SQL.

Shroudlaid answered 16/4, 2012 at 21:22 Comment(1)
it may be worth noting the problems this has with empty arrays.Huynh
M
0

If you want to use sub-queries so that you get the dormitories IDs within the query, instead of using a separate query to get the values, then you can for example:

where(student_id: Dormitory.select(:id).some_scope)

If you use baby squeel

where.has { student_id.in Dormitory.select(:id).some_scope }

And with baby_squeel in case you actually want to join that table:

join(:dormitory).where.has { student.id.in Dormitory.select(:id).some_scope }
Malinger answered 8/7, 2024 at 21:11 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.