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
Written by Michael Kohl
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#