Translate every query in Rails to a SQL code

Ruby on Rails / Active Record

Rails to_sql method is a well-known method for Ruby programmers but mostly junior developers may not be familiarized with it yet. It’s super helpful so it’s worth to mention it once again.

Tell me the truth

to_sql method is a great debug tool, very useful if you want to learn how some magic code is working. ActiveRecord DSL is very pretty but under the hood, it generates SQL queries that are not that pretty and using to_sql exposes the truth:

Location.where(city: 'New York').to_sql

Subqueries

You will be mostly using to_sql for debugging but this method is also useful when it comes to writing more complicated subquery. Instead of writing raw SQL queries you can always build ActiveRecord query call and then pass to_sql at the end of it and pass the whole query to another query. Since it’s more advanced topic, I will not dive into it today.

Do you use some another super useful method like to_sql? Let us know in the comments section!