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.
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.
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