How to show SQL queries in Rails console?

When I run queries (e.g. MyModel.where(...) or record.associated_things ) in the console, how can I view the current database queries so that I can better understand what is happening?

+95
ruby-on-rails activerecord
May 29 '10 at 17:37
source share
6 answers

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) 
+217
May 29 '10 at 17:44
source share

In Rails 3+, you can use the ActiveRecord :: Relations to_sql :

 User.where(:id => 3).to_sql #=> "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"id\" = 3" 
+27
Dec 18 '14 at 5:59
source share

In Rails 4. there is a .explain method.
( .to_sql also works, but not displayed)

 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 
+20
Feb 01 '16 at 13:24
source share

Recently, you can use this:

https://github.com/dejan/rails_panel

It consists of the addition of the developer console panel for chrome and gem file, which must be added to your Gemfile application as follows:

 group :development do gem 'meta_request' end 

Then run again:

 bundle install 

Restart the application, open it and launch the developer console, and you will see the following: enter image description here

+1
Nov 12 '17 at 9:24 on
source share

Special requests ActiveRecord to the console does not work. In any case, change this behavior?

Are you sure about that? I use the console all the time for such things. For the development environment, the default behavior is to register requests to development.log. Are you sure you have not changed your journal level in your environment?

Do you see the following in development.rb?

 config.log_level = :debug 
0
May 29 '10 at 18:15
source share

I prefer to set the logging level in config/application.rb :

 config.after_initialize do Rails.logger.level = (ENV['LOG_LEVEL'] || Logger::INFO).to_i end 

In production, my ENV['LOG_LEVEL'] will be set to Logger::INFO , and on my local machine it will be Logger::DEBUG .

0
Aug 16 '19 at 7:29
source share



All Articles