我如何获得通过的ActiveRecord的Ruby on Rails的最后执行的SQL查询? [英] How do I get the last SQL query performed by ActiveRecord in Ruby on Rails?

查看:221
本文介绍了我如何获得通过的ActiveRecord的Ruby on Rails的最后执行的SQL查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找类似codeIgniter的:

I'm looking for something like CodeIgniter's:

$this->db->last_query();

(<一href="http://$c$cigniter.com/user_guide/database/helpers.html">http://$c$cigniter.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 ,你会看到一个名为日志的方法。这种方法被调用的每一个查询记录的声明。默认情况下,它会记录与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

现在,你可以得到与查询

Now you can get the query with

ActiveRecord::Base.connection.last_query # => ...

这篇关于我如何获得通过的ActiveRecord的Ruby on Rails的最后执行的SQL查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆