Ruby Activerecord IN子句 [英] Ruby Activerecord IN clause

查看:53
本文介绍了Ruby Activerecord IN子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人知道如何在activerecord中执行 IN子句。不幸的是, IN子句几乎不可谷歌搜索,所以我必须在这里发布。基本上,我想回答这样一个问题:给我所有这些宿舍中的大学生,这些宿舍的id都在此数组[id array]中。我知道在给定单个宿舍ID的情况下如何编写查询,但在给定ID数组的情况下我不知道如何执行查询。

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.

推荐答案

来自§2.3.3Rails指南的子集条件


如果要使用 IN 表达式查找记录,则可以传递
到条件哈希的数组:

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

Client.where(:orders_count => [1,3,5])

此代码将生成如下SQL:

This code will generate SQL like this:

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


您还可以使用 arel 语法:

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

将生成相同的SQL

这篇关于Ruby Activerecord IN子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆