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

Want to receive useful tips, information about new Ruby gems and articles on a daily basis? Make sure you follow me and say hello!

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!

Want to become a better Rails developer?
Download for free the Introduction Rails patterns book and dive into the world of refactoring and easy-testable Ruby code today.
Join over 1,000 developers already subscribed to my newsletter and download the book. You can unsubscribe anytime:

Subscribe and get the book!