Run Explain (and Anaylze) in Rails Console
If you're troubleshooting some slow SQL queries, chances are you've used EXPLAIN or even EXPLAIN ANALYZE. But TIL, that you can actually run these in the Rails console on your Rails models (Active Model Relations). It looks something like this -
> User.active.explain
Or if you're on a more recent version of Rails, you can also pass arguments to .explain, such as :analyze -
> User.active.explain(:analyze)
You can also call it on other methods like pluck, etc. -
> User.active.explain.pluck
Be warned that calling .explain will execute the query.
https://devdocs.io/rails~7.2/activerecord/relation#method-i-explain
https://guides.rubyonrails.org/active_record_querying.html#running-explain
Tweet