Active Record Ruby on Rails

Ruby on Rails / ActiveRecord – translate every query in a SQL code

Ruby on Rails / ActiveRecord – translate every query in a SQL code January 18, 20184 Comments

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!

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you. Subscribe to the newsletter to get a free copy of the book.

4 comments

  1. For Rails 2: MODEL_NAME.send(:construct_finder_sql, { :conditions => LIKE_YOU_USE_THEM_IN_ACTIVERECORD})

    If you actually execute the queries you could:
    1. Type “tail -f log/development.log” in another terminal window
    2. Type this in the Rails console and it will output each query on the screen:
    2.1 For Rails 2: ActiveRecord::Base.connection.instance_variable_set :@logger, Logger.new(STDOUT)
    2.2 For Rails 3+: ActiveRecord::Base.logger = Logger.new(STDOUT)

Leave a Reply

Your email address will not be published. Required fields are marked *