I was recently helping a developer with some SQL optimizations in Ruby. The developer was using Active Record, and (until now) my Active Record experience has been pretty minimal.
One thing that was really driving me bonkers was how to get Active Record to print out the queries it was building. I was certain we could get this thing humming along a little quicker if we could just get a peek at those queries!
This post regarding using ActiveRecord Without Rails had the answer I was looking for. Here's some code to get you rolling.
require 'rubygems'
require 'active_record'
require 'logger'
ActiveRecord::Base.establish_connection()
ActiveRecord::Base.logger = Logger.new(File.open('queries.log', 'w'))
You can also send your log to an existing filehandle such as ActiveRecord::Base.logger = Logger.new(STDERR)
and then redirect to a file on the command line. I actually logged this way and redirected to a temporary file with 2>
.