Samuel D.
Samuel D.

Reputation: 189

How to Query with multiple conditions on same field in Rails

I have this array:

cars = ["green", "blue", "red", "yellow"]

And I would like to conditionate with the same name field, for example:

Car.where(name: 'green', name: 'blue', name: 'red', name: 'yellow') 

I am looking for a condition where I can bring all the cars with those four names

Is there a more practical way to simplify the multiple conditions query? So that it can be optimal

Upvotes: 1

Views: 898

Answers (1)

Ursus
Ursus

Reputation: 30056

Car.where(name: ["green", "blue", "red", "yellow"])

this returns you a relation with rows of cars which have name green or blue or red or yellow. in SQL that translates to something like

SELECT cars.*
FROM cars
WHERE name IN ('green', 'blue', 'red', 'yellow') 

note that this hash

{ name: 'green', name: 'blue', name: 'red', name: 'yellow' }

the one you passed to where, always evaluates to

{ name: 'yellow' }

because you can't instantiate an hash with a key present more than once. the last one is kept

Upvotes: 1

Related Questions