to_sql not working on update_attributes or .save

2020-04-20 23:55发布

问题:

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 but it returns a TrueClass error (or something like that). Is there something that I am missing?

回答1:

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



回答2:

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