Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Record - Where IN with multiple columns

I have a query that needs to fetch from a table that meet two columns requirements exactly. So if I have users table with columns, age and score.

SELECT * FROM users where (age, score) IN ((5,6), (9,12), (22,44)..)

In my web app I am getting this pairs from an ajax request, and the number could be quite big. How do I construct an Active Record query for this?.

I am working on postgres database

like image 416
coderVishal Avatar asked May 12 '16 09:05

coderVishal


1 Answers

In rails 5, you can use OR, so you can do:

ages_and_scores = [ [5, 6], [9, 12], [22, 44] ]
ages_and_scores.map do |age, score|
  User.where(age: age).where(score: score)
end.reduce(&:or)
# => should produce something like:
# SELECT * FROM users WHERE (`users`.`age` = 5 AND `users`.`score` = 6 OR `users`.`age` = 9 AND `users`.`score` = 12 OR `users`.`age` = 22 AND `users`.`score` = 44)

I believe this is sql-injection free and pure ActiveRecord.

like image 105
Yuki Inoue Avatar answered Oct 04 '22 17:10

Yuki Inoue