Show ActiveRecord SQL in Rails 3 Console

If you want to show sql in your console for Active Record, then you may have run across the past Rails Recipes book or similar formulas for Rails < v3.0.  I just tweaked a formula I saw in that book to work with Rails 3 and here it is (This is designed to work on a Mac or most Linux flavors, Windows users, YMMV):

Create ~/.irbrc or add the following to your .irbrc, Mine is located at ~/.irbrc

if defined?(Rails) && Rails.env
  load File.dirname(__FILE__) + "/.railsrc"
end

Create ~/.railsrc or add the following to your ~/.railsrc:

def toggle_sql
  if ActiveRecord::Base.logger
    set_logger nil and return false
  else
    set_logger Logger.new(STDOUT) and return true
  end
end

def set_logger(logger)
  ActiveRecord::Base.logger = logger
  ActiveRecord::Base.clear_active_connections!
end
set_logger nil # start with the normal logger

Then, when you’re in your rails console world, just call toggle_sql. It returns true if the sql will be on, and false if the sql will be off.

Please feel free to leave suggestions and improvements here as I am always open to these suggestions.

Tags: , , , , ,

About the Author: JeffAncel
http://jeffancel.com
A passionate web developer in St. Louis. Living on the edge with Rails, HTML5, CSS3 and any interesting libraries around. I love to spend time with the family, cook, develop web applications and play with our dragons. When I have nothing else to do, I socialize via twitter (@jancel) and facebook.

Leave a reply

© 2012 - Jeff Ancel
Wordpress Themes
Scroll to Top