Bratish Goswami

Personal website and blog

When debugging Rails applications, it's super helpful to see the actual SQL queries being executed. By default, Rails console doesn't show you the database queries, which can make debugging a pain.

Here's how to enable SQL logging in Rails console:

Method 1: Enable for current session

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

Now when you run queries, you'll see the SQL:

User.find(1)
# User Load (0.3ms)  SELECT * FROM `users` WHERE `users`.`id` = 1 LIMIT 1

Method 2: For Rails 3+ with colored output

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

Method 3: Make it permanent

Add this to your ~/.irbrc file:

if defined?(Rails) && Rails.env
  ActiveRecord::Base.logger = Logger.new(STDOUT)
  ActiveRecord::Base.colorize_logging = true
end

Method 4: One-liner in console

ActiveRecord::Base.connection.instance_variable_set(:@logger, Logger.new(STDOUT))

Method 5: Enable for specific queries only

# Temporarily enable logging
old_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = Logger.new(STDOUT)
User.find(1)  # This will show SQL
ActiveRecord::Base.logger = old_logger  # Restore

Method 6: Using Rails.logger instead

ActiveRecord::Base.logger = Rails.logger

Method 7: Custom logger with different levels

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

This is incredibly useful when you want to:

  • Debug slow queries
  • Understand what ActiveRecord is actually doing
  • Optimize your database calls
  • Learn SQL by seeing what Rails generates

The colored output makes it much easier to spot the SQL queries among all the other console output.