Use to_sql without slashes

Do you hate slashes in your to_sql output? Then this post is for you!

This is such a simple thing, but something that has already improved my quality of life when debugging SQL queries in a Rails console!

Have you ever done something like;

Thing.all.to_sql

To better understand what SQL ActiveRecord is generating?

This will return something like;

Thing.all.to_sql
=> "SELECT \"things\".* FROM \"things\"

I dislike those slashes a lot, they add a lot of visual noise.

If you take the output of to_sql and add it into puts, the slashes go away!

puts Thing.all.to_sql
"SELECT "things".* FROM "things"
=> nil

Interestingly, this behaviour is similar to when you inspect a String;

'test'.inspect
 => "\"test\""

puts 'test'.inspect
"test"
 => nil

So, yeah, use puts Blah.something.to_sql to have more readable output!

If you’re wondering what the => nil means in the output, puts will do what it is meant to do (put out a line) and then return nil, so we’re just seeing the returned value of puts.


Recent posts View all

Ruby

Forcing a Rails database column to be not null

How you can force a table column to always have something in it with Rails

Writing Marketing

We've deleted an article's worth of unhelpful words

We've improved several pages across our site by removing words that add no value, and often detract from the article.