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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With