How do I get the last SQL query performed by ActiveRecord in Ruby on Rails?

后端 未结 3 2014
不思量自难忘°
不思量自难忘° 2020-12-09 06:04

I\'m looking for something like CodeIgniter\'s:

$this->db->last_query();

(http://codeigniter.com/user_guide/database/helpers.html)

相关标签:
3条回答
  • 2020-12-09 06:45

    Probably because I have a newer version of ActiveRecord than when this question was asked, but to get it to work with ActiveRecord 3.2.3 I updated the script of Simone Carletti: I added the extra attribute binds and moved the call to alias_method_chain below the method definition because otherwise it would raise an error saying that it can't find the method.

    ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do
    
      attr_reader :last_query
    
      def log_with_last_query(sql, name, binds=[], &block)
        @last_query = [sql, name]
        log_without_last_query(sql, name, binds, &block)
      end
      alias_method_chain :log, :last_query
    
    end
    

    Getting the last query is still the same:

    ActiveRecord::Base.connection.last_query # => ...
    
    0 讨论(0)
  • 2020-12-09 06:51

    Your development log should include all SQL queries that are run.

    0 讨论(0)
  • 2020-12-09 06:58

    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.

    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.

    You can do something like

    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 # => ...
    
    0 讨论(0)
提交回复
热议问题