Showing posts with label sql. Show all posts
Showing posts with label sql. Show all posts

Thursday, July 16, 2015

How to discover what is generating an SQL statement in your Rails log

Just spreading a really cool tip I came across. Ryan Bigg has this blog post showing how you can find out what is creating an SQL statement in your log. I was having a devil of a time figuring out where a particular callback was coming from and discovered his great post. Essentially you hook into ActiveSupport::Notifications and then put in logic in the regex piece to describe the query you are looking for. In this case I did this in development.rb:
  ActiveSupport::Notifications.subscribe('sql.active_record') do |_, _, _, _, details|  
   if details[:sql] =~ /UPDATE "answers" SET position =/  
    puts '*' * 50  
    puts caller.join("\n")  
    puts '*' * 50  
   end  
  end  
And then looked at the call stack to see where it was coming from. I could have output to the logger too. And I would not recommend doing this on Production.