Skip to content

Instantly share code, notes, and snippets.

@loicginoux
Last active September 24, 2019 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loicginoux/a504033cfbe9065da1c23b45cbd79eaa to your computer and use it in GitHub Desktop.
Save loicginoux/a504033cfbe9065da1c23b45cbd79eaa to your computer and use it in GitHub Desktop.
how to know which sql query comes from which line of code
# file config/initializers/active_record_log_subscriber.rb
###
# log result:
# Alert Load (0.8ms) SELECT `alerts`.* FROM `alerts` INNER JOIN `sharings` ON `alerts`.`id` = `sharings`.`alert_id` WHERE `sharings`.`user_id` = 37 AND `alerts`.`id` = 54148 AND (status = 0) LIMIT 1
# ↳ app/controllers/entries_controller.rb:20:in `set_objects'
# source: http://www.jkfill.com/2015/02/14/log-which-line-caused-a-query/
###
module LogQuerySource
def debug(*args, &block)
return unless super
backtrace = Rails.backtrace_cleaner.clean caller
relevant_caller_line = backtrace.detect do |caller_line|
!caller_line.include?('/initializers/')
end
if relevant_caller_line
logger.debug(" ↳ #{ relevant_caller_line.sub("#{ Rails.root }/", '') }")
end
end
end
ActiveRecord::LogSubscriber.send :prepend, LogQuerySource
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment