问题
How do I trace which SQL query did my Activerecord methods generated (eg find, where).
回答1:
You can debug ActiveRecord queries from a console.
Hit rails console
and enter:
ActiveRecord::Base.logger = Logger.new(STDOUT)
回答2:
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.
回答3:
You can call to_sql
on relation objects (like that returned when you call where
) to get the SQL for those queries.
回答4:
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!
来源:https://stackoverflow.com/questions/9173448/retrieving-sql-queries-from-active-record-queries-in-rails-3