简体   繁体   English

从Rails 3中的活动记录查询中检索SQL查询

[英]Retrieving sql queries from Active-record queries in Rails 3

我如何跟踪我的Activerecord方法生成了哪个SQL查询(例如,find,where)。

You can debug ActiveRecord queries from a console. 您可以从控制台调试ActiveRecord查询。

Hit rails console and enter: 点击rails console并输入:

ActiveRecord::Base.logger = Logger.new(STDOUT)

I assume you're using Rails 3.0.x, you can do that by configuring your active record. 我假设您使用的是Rails 3.0.x,可以通过配置活动记录来做到这一点。 Put this in config/environments/development.rb 把它放在config/environments/development.rb

# Log ActiveRecord
ActiveRecord::Base.logger = Logger.new(STDOUT) if defined?
Rails::Console

Now, every query is explained in console. 现在,将在控制台中解释每个查询。

您可以在关系对象上调用to_sql (类似于调用where时返回的对象),以获取这些查询的SQL。

If you want to do it permanently (always show queries in console) just add those files: 如果要永久执行此操作(总是在控制台中显示查询),只需添加以下文件:

~/.rvmrc 〜/ .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 〜/ .railsrc

require 'active_record'

ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.clear_active_connections!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM