Everything I Plan on Forgetting

notes and cool things on the stupid stuff i do

Rails: View SQL queries in the console

So you see the queries in your rails server log as you are playing with your app, but what about when you are testing in console?  I'm sure there are other ways to do it, but this does the trick.  Just start up your rails console and type this line in. 

ActiveRecord::Base.logger = Logger.new(STDOUT)

Look at the awesomeness.

script/console
Loading development environment (Rails 2.3.10)
>> ActiveRecord::Base.logger = Logger.new(STDOUT)
=> #<Logger:0x103332350 @formatter=nil, @level=0, @default_formatter=#<Logger::Formatter:0x103332300 @datetime_format=nil>, @progname=nil, @logdev=#<Logger::LogDevice:0x1033322b0 @filename=nil, @mutex=#<Logger::LogDevice::LogDeviceMutex:0x103332260 @mon_entering_queue=[], @mon_count=0, @mon_owner=nil, @mon_waiting_queue=[]>, @dev=#<IO:0x100177ba8>, @shift_size=nil, @shift_age=nil>>
>> Campaign.find :first
  SQL (0.2ms)   SET NAMES 'utf8'
  SQL (0.1ms)   SET SQL_AUTO_IS_NULL=0
  Campaign Load (0.4ms)   SELECT * FROM `campaigns` LIMIT 1
  Campaign Columns (9.6ms)   SHOW FIELDS FROM `campaigns`

On the topic on viewing queries, a cool rails 3 tip is the .to_sql method



rails c
Loading development environment (Rails 3.0.5)
ruby-1.9.2-p136 :001 > ExtractionLink.where(:status => 'new').order('name').to_sql
 => "SELECT `extraction_links`.* FROM `extraction_links` WHERE `extraction_links`.`status` = 'new' ORDER BY name"


 

Filed under  //   console   programming   rails   rails2   rails3   ruby   sql