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)":
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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.