如何在 Ruby on Rails 中获取 ActiveRecord 执行的最后一个 SQL 查询? [英] How do I get the last SQL query performed by ActiveRecord in Ruby on Rails?
问题描述
我正在寻找类似 CodeIgniter 的东西:
I'm looking for something like CodeIgniter's:
$this->db->last_query();
(http://codeigniter.com/user_guide/database/helpers.html)
推荐答案
AFAIK,没有简单的方法来访问查询列表.尽管如此,您可以轻松访问它们,创建一个超级简单的记录器.
AFAIK, there's no easy way to access the list of queries. Nonetheless you can easily get access to them creating a super simple logger.
如果您打开类ActiveRecord::ConnectionAdapters::AbstractAdapter
,您将看到一个名为log 的方法.在每个查询上调用此方法以记录语句.默认情况下,它使用 Rails 记录器记录所有语句.
If you open the class ActiveRecord::ConnectionAdapters::AbstractAdapter
you'll see a method called log. This method is invoked on each query to log the statement. By default, it logs all the statements with the Rails logger.
你可以做类似的事情
ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do
attr_reader :last_query
alias_method_chain :log, :last_query
def log_with_last_query(sql, name, &block)
@last_query = [sql, name]
log_without_last_query(sql, name, &block)
end
end
现在您可以使用
ActiveRecord::Base.connection.last_query # => ...
这篇关于如何在 Ruby on Rails 中获取 ActiveRecord 执行的最后一个 SQL 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!