Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord Multiple WHERE Statements

I have an array that contains some conditions, say: ages = [1, 4, 10].

I am trying to build a query where it will return the ages in the array. The array can be of arbitrary length. So something like:

Person.where("age == :ages", {:ages => ages})

Now this obviously does not work as :ages would be an array, when according to the equality statement above, it's expecting a string.

I'm trying to have it achieve something along the lines of: WHERE age = 1 AND age = 4 AND age = 10 according to the ages array.

All examples online discuss how to use multiple where conditions when they are separate variables, in which case is easy as you would do: Person.where("condition1 = :first AND condition2 = :second....). I have unknown number of items in the array and I want to filter all my query result by them.

like image 694
darksky Avatar asked Mar 18 '26 07:03

darksky


1 Answers

It is already supported by ActiveRecord and the where statement:

ages = [1, 5, 12]
Person.where(age: ages)
# This will generates a query like:
# SELECT * FROM persons WHERE age IN(1, 5 ,12)

This way of querying is also better than 'hard-coding' condition (passing strings to the where statement). By using Hash parameters you let ActiveRecord deal with all the DB-Query translation work.

like image 179
MrYoshiji Avatar answered Mar 20 '26 20:03

MrYoshiji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!