Retrieving sql queries from Active-record queries in Rails 3

情到浓时终转凉″ 提交于 2019-12-22 18:24:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!