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