Last Updated: February 25, 2016
·
351
· mschae

See where your SQL queries come from

This is quite handy if you need to figure out (temporarily) where in your code queries originated.
I used this to enhance the speed of an export.

subscription = ActiveSupport::Notifications.subscribe('sql.active_record') do |*args|
  query       = args[4][:sql]
  local_stack = caller.select{|e| e.include?(Rails.root.to_s)}
  Logger.new("log/sql_debug.log").ap({query => local_stack})
end
# possibly expensive code goes here
ActiveSupport::Notifications.unsubscribe(subscription)