3

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.

1
  • You should accept one of the answers if it fits your questions Commented Jan 29, 2013 at 22:16

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I was doing it as Person.where(age => ages) which is apparently incorrect. Could you explain the colon syntax? And what the hash form of where means please?
The colon is Ruby 1.9 optional syntax for a Hash. { :age => ages } and { age: ages } are functionally identical.
Except that you cant assign a string in the new Ruby 1.9 Hash Syntax: { 'foo' => 'bar' } works when { 'foo': 'bar' } does not.
2

I think you're looking for an IN query since age cannot be both 1 and 4 and 10 for some single column integer value.

Person.where(age: ages)

1 Comment

Nothing to do here but someone stole your profile picture on StackOverflow!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.