1

I want to query my database table where the age field have a value 24 or 26. I tried using 'like' in my query.

User.where('age like ? or age like ?',"%24%","%26%")

Am I doing something wrong here?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99

3 Answers3

0

try this

User.where("age in ?",["24","26"])

Let consdier your age in string with comma delimiter

ages = "24,26,28,17,18"
age_array = ages.split(",")
User.where("age in ?",age_array)
Sachin R
  • 11,606
  • 10
  • 35
  • 40
  • I believe @polurupraveen is looking one with LIKE – sameera207 Jun 03 '13 at 07:26
  • @sameera207 but he doesnt have to when he is only checking for exact number, right? – pahnin Jun 03 '13 at 07:27
  • That will match the field values exactly. I want to query using a regular expression because my user age is a string with commas as delimiter –  Jun 03 '13 at 07:28
  • @polurupraveen then you can try converting the string to int – pahnin Jun 03 '13 at 07:29
  • @JohnnyB-- Ages are comma separated in the database. Not in a variable –  Jun 03 '13 at 07:35
  • @polurupraveen I just give an example ages varaible value can be assigned from database column too. – Sachin R Jun 03 '13 at 07:37
  • Sorry for the trouble guys. My query was correct except for an extra comma when i tried in my console. My bad. Thanks for helping and sorry again –  Jun 03 '13 at 07:41
  • 1
    `User.where("age in ?",["24","26"])` will give you syntax error you have to use `User.where("age in (?)",["24","26"])` note for `()` surrounding the `?` – Salil Jun 03 '13 at 07:46
  • @polurupraveen Please delete the question if it was just a typo. – Substantial Jun 03 '13 at 08:02
0

You can try this too ..

User.where(:age => age_array)
sushilprj
  • 2,203
  • 1
  • 14
  • 19
0

Use this pattern for multiple search attributes:

ages = ["24", "26"]
query = ages.map { |age| "age like '%#{age}%'" }.join(" OR ")
User.where(query)

It will auto generate a query like this:

SELECT 'users.*' FROM 'users' WHERE (age like '%24%' OR age like '%26%')

Hope this solution will help you!

Alex Chen
  • 41
  • 2