Last Updated: February 25, 2016
·
284
· glenn

Thinking idiomatically with Rails queries

Hey there, friend. If you're forgetful like me, you may appreciate a quick refresher on rails conditional statements.

So, you know you can do this:

User.where(id: 1)

#=> "SELECT `users`.* FROM `users`  WHERE `users`.`id` = 1"

Did you know you can pass a range?

User.where(id: 1..10)

#=> "SELECT `users`.* FROM `users`  WHERE (`users`.`id` BETWEEN 1 AND 10)"

How about a list?

User.where(id: [1, 3, 5])

#=> "SELECT `users`.* FROM `users`  WHERE `users`.`id` IN (1, 3, 5)"

How about a list... of ranges?

User.where(id: [1..10, 20..30, 40..50])

#=> "SELECT `users`.* FROM `users`  WHERE ((((`users`.`id` BETWEEN 1 AND 10 OR `users`.`id` BETWEEN 20 AND 30) OR `users`.`id` BETWEEN 40 AND 50) OR 1=0))"

If you knew that already then great! But don't worry if you didn't.

Like Ruby, the Active Record query interface operates based on the Principle Of Least Astonishment. So, the next time you have to construct a complicated query, think idiomatic ruby and run it in your REPL. You may be astonished to find that it works just as you expected.

Have a good day!