CubicLouve

Spring_MTの技術ブログ

ActiveRecordでEXPLAINをする

ActiveRecord::Relation には explain メソッドがあります。

github.com

このメソッドを使えば、ActiveRecord経由からでも EXPLAIN を打つことができます。

[11] pry > User.joins(:hoge).where(bar_id: 1).class
=> User::ActiveRecord_Relation
[12] pry > User.joins(:hoge).where(bar_id: 1).explain
=> EXPLAIN for: SELECT `users`.* FROM `users` INNER JOIN `hoges` ON `hoges`.`id` = `users`.`hoge_id` WHERE `users`.`bar_id` = 1
+----+-------------+----------+------------+--------+-----------------------------------------------------------------------------------------+---------------------------+---------+-----------------------------------------+------+----------+-------------+
| id | select_type | table    | partitions | type   | possible_keys                                                                           | key                       | key_len | ref                                     | rows | filtered | Extra       |
+----+-------------+----------+------------+--------+-----------------------------------------------------------------------------------------+---------------------------+---------+-----------------------------------------+------+----------+-------------+
|  1 | SIMPLE      | users    | NULL       | ref    | xxxx,xxxx | xxxx  | 4       | const                                   |    1 |     20.0 | Using where |
|  1 | SIMPLE      | hoges | NULL       | eq_ref | PRIMARY                                                                                 | PRIMARY                   | 4       | xxxx.users.hoge_id |    1 |    100.0 | Using index |
+----+-------------+----------+------------+--------+-----------------------------------------------------------------------------------------+---------------------------+---------+-----------------------------------------+------+----------+-------------+
2 rows in set (0.00 sec)

EXPLAINの内容は適当に変更しているので気にしないでください

ただしあくまで、リレーションにだけ適用できるので、find とかには使えません。

参照

railsguides.jp