Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm looking for something like CodeIgniter's:

$this->db->last_query();

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

like image 350
Nikki Erwin Ramirez Avatar asked Jul 07 '09 07:07

Nikki Erwin Ramirez


1 Answers

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 # => ...
like image 88
Simone Carletti Avatar answered Sep 26 '22 02:09

Simone Carletti