Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify multiple values in where with AR query interface in rails3

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

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: wrong number of bind variables (1 for 5)

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.

like image 554
wkhatch Avatar asked Feb 17 '11 22:02

wkhatch


1 Answers

This is actually pretty simple:

Model.where(attribute: [value1,value2]) 
like image 141
nfriend21 Avatar answered Oct 09 '22 00:10

nfriend21