Monday, December 21, 2009

Display SQL queries in ruby script/console

Whenever we use ruby script/console during development, we often would like to see the SQL queries instantly that get being generated at the backend. Those queries can be a result of method calls on model, named scope, etc.

We just need to execute the below 2 lines to have this enabled on console.

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


And now whenever we will interact with ActiveRecord object method calls, the SQL query will get displayed immediately in the console.

e.g.

2 comments:

  1. Great tip, Niranjan! Thanks a lot for posting this.

    ReplyDelete
  2. Liked the idea to go frictionless and improve performance :)

    I Found something which might be relevant for loggers. I was wondering how to use logger.info method in lib or extensions.
    Say, in lib file you want to say logger.info("XYZ")
    this will throw an error!

    Rails 2.3.x provides a way to implement that:
    Rails.logger.info("XYZ")

    ReplyDelete