Rails ActiveRecord Multiple WHERE Clauses

I have an array that contains some of the conditions, for example ages = [1, 4, 10]

.

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

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

      

Now this obviously doesn't work as it :ages

will be an array when, as per the above equality statement, it expects a string.

I'm trying to achieve something line by line: WHERE age = 1 AND age = 4 AND age = 10

as per array ages

.

All examples are online discussing how to use multiple conditions, when they are separate variables, and in this case it is easy, as you do: Person.where("condition1 = :first AND condition2 = :second....)

. I have an unknown number of elements in an array and I want to filter all the results of my query.

+3


source to share


2 answers


It is already supported by ActiveRecord and the where clause:

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

      



This query method is also better than the "hard-coded" clause (passing strings to the where clause). By using Hash parameters, you let ActiveRecord handle all of the DB-Query translation work.

+2


source


I think you are looking for a request IN

, as age

can be like 1

, and 4

and 10

for some integer column.



Person.where(age: ages)

      

+2


source







All Articles