Ruby Activerecord IN 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10181864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby Activerecord IN clause
提问by Black Dynamite
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.
我想知道是否有人知道如何在 activerecord 中执行“IN”子句。不幸的是,“IN”子句几乎无法用 Google 搜索,所以我必须在这里发帖。基本上我想回答这样的问题“给我这些宿舍里的所有大学生,其中宿舍id在这个数组[id数组]中”。我知道如何在给定单个宿舍 ID 的情况下编写查询,但在给定一组 id 的情况下,我不知道该怎么做。
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.
任何帮助是极大的赞赏。我确定这是某个问题的转帖,因此一旦找到答案/更好的搜索词,我将删除它。
回答by Chen Kinnrot
From §2.3.3 Subset Conditions of the Rails Guides:
If you want to find records using the
INexpression you can pass an array to the conditions hash:Client.where(:orders_count => [1,3,5])This code will generate SQL like this:
SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
如果要使用
IN表达式查找记录,可以将数组传递给条件哈希:Client.where(:orders_count => [1,3,5])此代码将生成如下 SQL:
SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
You can also use the arelsyntax:
您还可以使用arel语法:
Client.where(Client.arel_table[:order_count].in([1,3,5]))
Will generate the same SQL
将生成相同的 SQL

