[Rails] How to show raw sql in Rails console

Tags
Rails
Engineering
Created
Oct 11, 2023 02:57 AM
Edited
Oct 10, 2023
Description
Show raw sql in Rails

Enable logger

  • Works in Rails3+
ActiveRecord::Base.logger = Logger.new(STDOUT)

explain

  • Works in Rails 4
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

to_sql

  • Some methods or queries are not supported
some_query.to_sql

Source