41

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.

3
  • 2
    It'd be abundantly useful if you posted the code you're having difficulty with.
    – mharper
    Feb 17, 2011 at 22:22
  • well, the code Dan posted below is pretty much what I'm trying to do, except that I don't know how many conditions there will be, hence also don't know how many substitutions either. So, I assumed I could pass an array in containing the values to be substituted in as the second arg.
    – wkhatch
    Feb 18, 2011 at 6:49
  • "varying number of attributes chained together with either AND or OR between them" as I understand the condition either match any given attributes or match all but not mix of both. Like attribute = ? OR attribute2 = ? OR attribute3 = ? or attribute = ? AND attribute2 = ? AND attribute3 = ?.
    – Amit Patel
    Sep 27, 2012 at 8:02

7 Answers 7

57

This is actually pretty simple:

Model.where(attribute: [value1,value2])
1
  • 3
    yes, this works great when you know how many possible values to or against when you're constructing the query, but I was looking for how to do it against an unknown number of possible options. I ended up splatting the array, I believe.
    – wkhatch
    Oct 4, 2014 at 0:50
29

Sounds like you're doing something like this:

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

Whereas you need to do this:

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

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

4
  • 1
    yes, the problem is that I don't know how many of these conditions there will be until runtime, so I'm dynamically constructing the first string argument. I suppose I could just insert the values I need to match against in the string, but that would be less safe certainly. It would seem that there's got to be a simpler way to pass multiple value arguments, but I guess not. Thanks for the reply
    – wkhatch
    Feb 18, 2011 at 6:44
  • 16
    I haven't tried it, but you could try using the splat operator on your array of argument values: Model.where("attributes = ?", *array_of_values)
    – dnch
    Feb 20, 2011 at 22:14
  • It won't work if you use it as is with "attributes = ?". You need to chain together your attribute names so that you get a string of the form "attribute1 = ? OR attribute2 = ? AND ...", then in place of the array of values pass the array itself prepended with the splat operator. Jan 27, 2013 at 12:17
  • sorry Dan Cheail, another person just commented on this, and I just realized I'd never given you the answer credit for this. My apologies sir. All the comments here were very helpful in solving my problem, in particular the splat idea, which was the main thing, and then making sure that when you do that, you're also using multiple conditions per shioyama
    – wkhatch
    May 1, 2015 at 21:21
28

Instead of passing the same parameter multiple times to where() like this

User.where(
  "first_name like ? or last_name like ? or city like ?", 
  "%#{search}%", "%#{search}%", "%#{search}%"
)

you can easily provide a hash

User.where(
  "first_name like :search or last_name like :search or city like :search",
  {search: "%#{search}%"}
)

that makes your query much more readable for long argument lists.

0
14

Sounds like you're doing something like this:

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

Whereas you need to do this:

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

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

Was really close. You can turn an array into a list of arguments with *my_list.

Model.where("id = ? OR id = ?", *["1", "2"])

OR

params = ["1", "2"]
Model.where("id = ? OR id = ?", *params)

Should work

1
  • Thanks Max. That's what I ultimately did, and I'm glad you posted this anyway, because I never went back and gave the original answer person credit for it, which I'm doing now. I have to give it to him, because he was first, but thanks for the answer all the same. It's right on the money
    – wkhatch
    May 1, 2015 at 21:18
6

If you want to chain together an open-ended list of conditions (attribute names and values), I would suggest using an arel table.

It's a bit hard to give specifics since your question is so vague, so I'll just explain how to do this for a simple case of a Post model and a few attributes, say title, summary, and user_id (i.e. a user has_many posts).

First, get the arel table for the model:

table = Post.arel_table

Then, start building your predicate (which you will eventually use to create an SQL query):

relation = table[:title].eq("Foo")
relation = relation.or(table[:summary].eq("A post about foo"))
relation = relation.and(table[:user_id].eq(5))

Here, table[:title], table[:summary] and table[:user_id] are representations of columns in the posts table. When you call table[:title].eq("Foo"), you are creating a predicate, roughly equivalent to a find condition (get all rows whose title column equals "Foo"). These predicates can be chained together with and and or.

When your aggregate predicate is ready, you can get the result with:

Post.where(relation)

which will generate the SQL:

SELECT "posts".* FROM "posts"
WHERE (("posts"."title" = "Foo" OR "posts"."summary" = "A post about foo")
AND "posts"."user_id" = 5)

This will get you all posts that have either the title "Foo" or the summary "A post about foo", and which belong to a user with id 5.

Notice the way arel predicates can be endlessly chained together to create more and more complex queries. This means that if you have (say) a hash of attribute/value pairs, and some way of knowing whether to use AND or OR on each of them, you can loop through them one by one and build up your condition:

relation = table[:title].eq("Foo")
hash.each do |attr, value|
  relation = relation.and(table[attr].eq(value))
  # or relation = relation.or(table[attr].eq(value)) for an OR predicate
end
Post.where(relation)

Aside from the ease of chaining conditions, another advantage of arel tables is that they are independent of database, so you don't have to worry whether your MySQL query will work in PostgreSQL, etc.

Here's a Railscast with more on arel: http://railscasts.com/episodes/215-advanced-queries-in-rails-3?view=asciicast

Hope that helps.

2

You can use a hash rather than a string. Build up a hash with however many conditions and corresponding values you are going to have and put it into the first argument of the where method.

1
  • This is the way to go, especially if you don't know how many params in advance. May 27, 2015 at 17:07
1

WRONG This is what I used to do for some reason.

keys = params[:search].split(',').map!(&:downcase)
# keys are now ['brooklyn', 'queens']

query = 'lower(city) LIKE ?'

if keys.size > 1
  # I need something like this depending on number of keys 
  # 'lower(city) LIKE ? OR lower(city) LIKE ? OR lower(city) LIKE ?'
 query_array = []
 keys.size.times { query_array << query }
 #['lower(city) LIKE ?','lower(city) LIKE ?']
 query = query_array.join(' OR ')
 # which gives me 'lower(city) LIKE ? OR lower(city) LIKE ?'
end
# now I can query my model
# if keys size is one then keys are just 'brooklyn', 
# in this case it is  'brooklyn', 'queens'
# @posts = Post.where('lower(city) LIKE ? OR lower(city) LIKE ?','brooklyn', 'queens' )
@posts = Post.where(query, *keys )

now however - yes - it's very simple. as nfriend21 mentioned

Model.where(attribute: [value1,value2])

does the same thing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.