How to show SQL queries run in the Rails console?
There is the .explain
method in Rails 4.
(.to_sql
works too, but won't show includes)
Category.includes(:products).explain
=> EXPLAIN for: SELECT "categories".* FROM "categories" 0|0|0|SCAN TABLE categories
EXPLAIN for: SELECT "categories_products".* FROM "categories_products" WHERE "categories_products"."category_id" IN (1, 2) 0|0|0|SCAN TABLE categories_products
EXPLAIN for: SELECT "products".* FROM "products" WHERE "products"."id" IN (1, 2, 3, 4, 5, 6, 7) 0|0|0|SEARCH TABLE products USING INTEGER PRIMARY KEY (rowid=?) 0|0|0|EXECUTE LIST SUBQUERY 1
In Rails 3+ you can use ActiveRecord::Relation’s to_sql
method:
User.where(:id => 3).to_sql
#=> "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"id\" = 3"
I just wanted to give our production console the same behavior I’m used to on dev, where all SQL queries are reported to the console.
Rails.logger.level = 0
3.0.3 :001 > Rails.logger.level = 0
=> 0
3.0.3 :002 > User.last
User Load (0.7ms) SELECT `users`.* FROM `users` ORDER BY `users`.`id` DESC LIMIT 1
=> #<User:…>
Rails 3+
Enter this line in the console:
ActiveRecord::Base.logger = Logger.new(STDOUT)
Rails 2
Enter this line in the console:
ActiveRecord::Base.connection.instance_variable_set :@logger, Logger.new(STDOUT)