to_sql not working on update_attributes or .save

后端 未结 2 759
青春惊慌失措
青春惊慌失措 2021-01-25 21:16

I\'m looking for a way to store the sql string that is generated in an update or create action. I\'ve tried appending .to_sql to the end of update_attributes<

相关标签:
2条回答
  • 2021-01-25 21:56

    In brief - you need to override ActiveRecord execute method. There you can add any logic for logging.

    connection = ActiveRecord::Base.connection
    class << connection
      alias :original_exec :execute
      def execute(sql, *name)
        # try to log sql command but ignore any errors that occur in this block
        # we log before executing, in case the execution raises an error
        begin
            file = File.open(RAILS_ROOT + "/log/sql.txt",'a'){|f| f.puts Time.now.to_s+": "+sql}
        rescue Exception => e
          ;
        end
        # execute original statement
        original_exec(sql, *name)
      end
    end
    

    credits:

    https://stackoverflow.com/a/1629474/643500

    https://stackoverflow.com/a/1640560/643500

    0 讨论(0)
  • 2021-01-25 22:00

    These methods both return a boolean. You can't invoke to_sql on a boolean.

    0 讨论(0)
提交回复
热议问题