Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 286
Hawkeye001 Avatar asked Feb 13 '23 05:02

Hawkeye001


1 Answers

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.

like image 78
Mischa Avatar answered Feb 15 '23 09:02

Mischa