Last Updated: May 18, 2017
·
1.417K
· citizen428

Trace SQL queries back to Rails code

Based on a blog post by Ryan Bigg, throw the following into an initializer to trace SQL queries in your logs. The environment variable DEBUG_QUERIES is used to turn tracing on/off, whereas QUERY_TO_DEBUG contains the actual query you are looking for (will be interpolated into a regex):

if ENV['DEBUG_QUERIES']
  query_regex = /#{ENV['QUERY_TO_DEBUG']}/
  ActiveSupport::Notifications.subscribe('sql.active_record') do |_, _, _, _, details|
    if details[:sql] =~ query_regex
      puts '*' * 50
      puts details[:sql]
      puts caller.join("\n")
      puts '*' * 50
    end
  end
end