如何在rails3中使用AR查询界面在where中指定多个值 [英] How to specify multiple values in where with AR query interface in rails3

查看:15
本文介绍了如何在rails3中使用AR查询界面在where中指定多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Active Record 查询界面上 Rails 指南的第 2.2 节此处:

Per section 2.2 of rails guide on Active Record query interface here:

这似乎表明我可以传递一个指定条件的字符串,然后传递一个值数组,这些值应该在构建 arel 时在某个时刻被替换.所以我有一个语句来生成我的条件字符串,它可以是不同数量的属性,它们之间用 AND 或 OR 链接在一起,我将一个数组作为第二个参数传递给 where 方法,我得到:

which seems to indicate that I can pass a string specifying the condition(s), then an array of values that should be substituted at some point while the arel is being built. So I've got a statement that generates my conditions string, which can be a varying number of attributes chained together with either AND or OR between them, and I pass in an array as the second arg to the where method, and I get:

ActiveRecord::PreparedStatementInvalid: 绑定变量的数量错误(1 对 5)

ActiveRecord::PreparedStatementInvalid: wrong number of bind variables (1 for 5)

这让我相信我做错了.但是,我没有找到有关如何正确执行此操作的任何信息.以另一种方式重申这个问题,我需要将一个字符串传递给 where 方法,例如table.attribute = ? AND table.attribute1 = ? OR table.attribute1 = ?"使用未知数量的这些条件和或或运算在一起,然后传递一些东西,我认为将是一个数组作为第二个参数,用于替换第一个参数条件字符串中的值.这是正确的方法,或者,我只是在某处错过了其他一些巨大的概念,而我完全错了?我认为以某种方式,这必须是可能的,而不仅仅是生成一个原始的 sql 字符串.

which leads me to believe I'm doing this incorrectly. However, I'm not finding anything on how to do it correctly. To restate the problem another way, I need to pass in a string to the where method such as "table.attribute = ? AND table.attribute1 = ? OR table.attribute1 = ?" with an unknown number of these conditions anded or ored together, and then pass something, what I thought would be an array as the second argument that would be used to substitute the values in the first argument conditions string. Is this the correct approach, or, I'm just missing some other huge concept somewhere and I'm coming at this all wrong? I'd think that somehow, this has to be possible, short of just generating a raw sql string.

推荐答案

听起来你正在做这样的事情:

Sounds like you're doing something like this:

Model.where("attribute = ? OR attribute2 = ?", [value, value])

而您需要这样做:

# notice the lack of an array as the last argument
Model.where("attribute = ? OR attribute2 = ?", value, value)

看看 http://guides.rubyonrails.org/active_record_querying.html#数组条件 了解有关其工作原理的更多详细信息.

Have a look at http://guides.rubyonrails.org/active_record_querying.html#array-conditions for more details on how this works.

这篇关于如何在rails3中使用AR查询界面在where中指定多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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