Hawkeye001
Hawkeye001

Reputation: 811

Rails using ActiveRecord "where" when parameter takes an Array

I am trying to use a rails "where" query using activeRecord. The query i have contains multiple conditions, one of which is an array:

User.where("state = ? AND salary >= ?", ["AL", "MI", "MA"], 1000)

The problem is that when I run it (either from a controller, or from a console), I don't get any errors, but what looks like an empty ActiveRecord object. If I have just one value in the array, it works fine. Its multiple values (that I know exist), that doesn't return the expected values.

SELECT `users`.* FROM `users` WHERE (salary >= 1000 AND state = "AL", "MI","MA")

I can use a hash instead, except I am not sure how to get all my conditions in the query in that regard. That, I can do the following:

User.where(state: ["AL", "MI", "MA"])

And that works, but not sure how to have the salary >= condition in there as well. Can anyone tell me what I am doing wrong, and how to resolve it?

Upvotes: 6

Views: 5232

Answers (2)

Mischa
Mischa

Reputation: 43298

I'd prefer to use Mark's solution, but to make your initial attempt work, you have to change state = ? to state IN (?), like this:

User.where("state IN (?) AND salary >= ?", ["AL", "MI", "MA"], 1000)

This will generate a WHERE ... IN ('...', '...') query, which is what you need when passing an array.

The advantage of using a hash is that Rails automatically generates the correct SQL. It does matter if you pass a string or an array.

Upvotes: 7

Mark Thomas
Mark Thomas

Reputation: 37517

Simply chain the where clauses:

User.where(state: ["AL", "MI", "MA"]).where("salary >= ?", 1000)

Upvotes: 4

Related Questions