to_sql not working on update_attributes or .save

2020-04-20 23:59发布

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?

2条回答
够拽才男人
2楼-- · 2020-04-21 00:46

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

查看更多
我命由我不由天
3楼-- · 2020-04-21 00:51

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

查看更多
登录 后发表回答