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

时间:2011-06-20 20:56:24

标签: ruby-on-rails

我正在尝试构建一个条件数组,以便在预准备语句中使用:

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

我已尝试执行以下操作但收到错误“ActiveRecord :: PreparedStatementInvalid(错误的绑定变量数量(4 for for 2)”:

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

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

为准备好的陈述构建条件的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

问题是你正在构建一个错误的查询,因为你通过语句将params传递给了问号。

您生成的查询如下所示:

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

为了达到你想要的阵列,你必须做这样的事情。

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

如果您重复上一步,则应获得所需的结果。

答案 1 :(得分:0)

您可能会发现使用哈希更容易:

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

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