How to get the latest SQL query executed by ActiveRecord in Ruby on Rails?

I am looking for something like CodeIgniter's:

$this->db->last_query(); 

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

+7
ruby ruby-on-rails activerecord
source share
3 answers

AFAIK, there’s no easy way to access the list of queries. However, you can easily access them by creating a super simple registrar.

If you open the ActiveRecord::ConnectionAdapters::AbstractAdapter class, you will see a method called a log. This method is called for each logging request. By default, it logs all statements using 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 request with

 ActiveRecord::Base.connection.last_query # => ... 
+23
source share

Perhaps because I have a newer version of ActiveRecord than when this question was asked, but to work with ActiveRecord 3.2.3, I updated Simone Carletti's script: I added an additional binds attribute and moved the alias_method_chain call below the method definition, because otherwise, it will cause an error stating that it cannot 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 request remains the same:

 ActiveRecord::Base.connection.last_query # => ... 
+2
source share

The development log should include all the SQL queries that are running.

0
source share

All Articles