Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show SQL queries run in the Rails console?

People also ask

How to see sql query in rails?

When you set log_level :info (mostly on production server), the SQL outputs are disabled in rails console . If you want to see SQL generated by Model. count , What you need is setting log level manually.

How do I view a rails database?

You can use rails dbconsole to view the database that your rails application is using. It's alternative answer rails db . Both commands will direct you the command line interface and will allow you to use that database query syntax.


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)

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"

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

Starting from Rails 6 there is more convenient approach: simply add ActiveRecord::Base.verbose_query_logs = true in console and you will see all SQL calls and places where it was called. More info https://guides.rubyonrails.org/debugging_rails_applications.html#verbose-query-logs


As from recently, you can use this:

https://github.com/dejan/rails_panel

It consists of developer console panel add-on for chrome, and gem file which needs to be added to your application's Gemfile like this:

group :development do
  gem 'meta_request'
end

Then run again:

bundle install

Restart your application, open it, and launch developer console, and you should see it like this: enter image description here