是否有任何适用于 Rails 3 的 gem 可以显示 我的代码的哪一部分生成了哪个 SQL 查询 ?
在 Rails 2.3 上有一个名为 query_trace 的插件,但它似乎不适用于 Rails 3,它会产生以下错误:
alias_method': undefined method `log_info' for class `ActiveRecord::ConnectionAdapters::AbstractAdapter' (NameError)
最佳答案
QueryTrace 无法按原样工作,因为在 Rails 3 中,尤其是在 ActiveRecord 区域中进行了许多更改。
所以,四处乱搞,我让它像这样工作:
您只需要提到的位置中的以下 2 个文件。然后重新启动 Web 服务器。
在 SQL 之后,您应该在控制台(白色洋红色)和日志文件中看到 Called from:
在 /vendor/plugins/query_trace/lib/query_trace.rb
module QueryTrace
def self.append_features(klass)
super
klass.class_eval do
unless method_defined?(:log_info_without_trace)
alias_method :log_info_without_trace, :sql
alias_method :sql, :log_info_with_trace
end
end
end
def log_info_with_trace(event)
log_info_without_trace(event)
logger.debug("\e[1m\e[35m\e[1m\e[47mCalled from:\e[0m " + clean_trace(caller[2..-2]).join("\n "))
end
def clean_trace(trace)
Rails.respond_to?(:backtrace_cleaner) ?
Rails.backtrace_cleaner.clean(trace) :
trace
end
end
在
/vendor/plugins/query_trace/init.rb
require 'query_trace'
class ::ActiveRecord::LogSubscriber
include QueryTrace
end
关于sql - 跟踪 Rails 3 SQL 查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4530870/