简体   繁体   English

Rails - 准备语句的构建条件数组

[英]Rails - Building Conditions Array for Prepared Statement

I'm trying build a conditions array to be using in a prepared statement: 我正在尝试构建一个条件数组以在预准备语句中使用:

Cars.find(:all, :conditions=>["color = ? AND doors = ? AND type = ?", "black", "4", "sedan"])

I've tried doing the following but getting an error of "ActiveRecord::PreparedStatementInvalid (wrong number of bind variables (4 for 2)": 我已尝试执行以下操作但收到错误“ActiveRecord :: PreparedStatementInvalid(错误的绑定变量数量(4 for for 2)”):

conditions = []
conditions += ["color = ?", "black"]
conditions += ["doors = ?", "4"]
conditions += ["type = ?", "sedan"]

Cars.find(:all, :conditions=>conditions)

What is the proper way of building a conditional for prepared statements? 为准备好的陈述构建条件的正确方法是什么?

The problem is that you are building a wrong query, since you pass the params to the questionmarks all the way through your statement. 问题是你正在构建一个错误的查询,因为你通过语句将params传递给了问号。

Your resulting query looks something like this: 您生成的查询看起来像这样:

 => ["color = ?", "black", "doors = ?", "4", "type = ?", "sedan"] 

In order to achieve your desired array, you would have to do something like this. 为了实现你想要的阵列,你必须做这样的事情。

conditions = []
conditions += ["color = ?", "black"]
array = ["doors = ?", "4"]
conditions[0].concat(" AND ")
conditions[0].concat(array[0])
conditions << array[1]

If you repeat the last steps, you should get your required result. 如果您重复最后一步,则应获得所需的结果。

You might find this easier to do with a hash: 您可能会发现使用哈希更容易:

conditions = {}
conditions[:color] = "black"
conditions[:doors] = 4
conditions[:type] = "sedan"

Cars.find(:all, :conditions=>conditions)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM