我想知道是否有人知道如何在 activerecord 中执行“IN”子句。不幸的是,“IN”子句几乎无法用谷歌搜索,所以我必须在这里发帖。基本上我想回答这样的问题“给我这些宿舍的所有大学生,宿舍 ID 在这个数组 [id 数组] 中”。我知道如何编写给定单个宿舍 ID 的查询,但我不知道如何给定一个 ID 数组。
非常感谢任何帮助。我确定这是某个问题的转贴,所以一旦找到答案/更好的搜索词,我将删除它。
最佳答案
来自 §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))
您还可以使用 arel语法:
Client.where(Client.arel_table[:order_count].in([1,3,5]))
将生成相同的 SQL。
关于Ruby Activerecord IN 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10181864/