jhbqyq
Last Updated: May 18, 2017
·
142
· citizen428
B3881a28fe402dd2d1de44717486cae8

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
Say Thanks
Respond