5

Show generated SQL in Rails 3 console

 2 years ago
source link: https://www.sethvargo.com/show-generated-sql-in-rails-3-console/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Show generated SQL in Rails 3 console

Have you ever wanted to see the resulting SQL of a query in Rails console? Well, unfortunately there's not really an 'easy' way to do this, other than hacking the console, so here we go.

Fire up your Rails console. I'm using Rails 3, but this should would in <3:

$ rails c
Loading development environment (Rails 3.0.7)
>> _

Cool, awesome, great. Now, we need to tell Rails console that we want to show what's being logged:

$ rails c
Loading development environment (Rails 3.0.7)
>> ActiveRecord::Base.logger = Logger.new(STDOUT)

We are creating a new instance of the ActiveRecord::Base#logger class. Normally, you would specify this as a file (for example, if you were performing an AR operation that you wanted to log separately from Application logs):

ActiveRecord::Base.logger = Logger.new('./logs/custom_log.log')

But in this case, we are simply "writing" to STDOUT. Now, when you run a query, you should see the supplemental query just as if you were viewing your development server logs!

About Seth

Seth Vargo is an engineer at Google. Previously he worked at HashiCorp, Chef Software, CustomInk, and some Pittsburgh-based startups. He is the author of Learning Chef and is passionate about reducing inequality in technology. When he is not writing, working on open source, teaching, or speaking at conferences, Seth advises non-profits.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK