How do I trace which SQL query did my Activerecord methods generated (eg find, where).
Asked
Active
Viewed 1,101 times
2
-
[This](http://stackoverflow.com/a/5492207/498594) answer gives you a lot of control - you get access to the queries in the app itself. – Kelvin Oct 12 '12 at 17:26
4 Answers
2
You can debug ActiveRecord queries from a console.
Hit rails console
and enter:
ActiveRecord::Base.logger = Logger.new(STDOUT)

shime
- 8,746
- 1
- 30
- 51
1
I assume you're using Rails 3.0.x, you can do that by configuring your active record. Put this in config/environments/development.rb
# Log ActiveRecord
ActiveRecord::Base.logger = Logger.new(STDOUT) if defined?
Rails::Console
Now, every query is explained in console.

Syed Aslam
- 8,707
- 5
- 40
- 54
1
You can call to_sql
on relation objects (like that returned when you call where
) to get the SQL for those queries.

Ryan Bigg
- 106,965
- 23
- 235
- 261
0
If you want to do it permanently (always show queries in console) just add those files:
~/.rvmrc
railsrc_path = File.expand_path('~/.railsrc')
if ( ENV['RAILS_ENV'] || defined? Rails ) && File.exist?( railsrc_path )
begin
load railsrc_path
rescue Exception
warn "Could not load: #{ railsrc_path }" # because of $!.message
end
end
~/.railsrc
require 'active_record'
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.clear_active_connections!

hsgubert
- 2,266
- 1
- 22
- 23