to_sql无法处理update_attributes或.save

我正在寻找一种方法来存储在更新或创建操作中生成的sql字符串。 我尝试将.to_sql附加到update_attributes的末尾,但它返回一个TrueClass错误(或类似的东西)。 有什么东西我不见了吗?

这些方法都返回一个布尔值。 您不能在布尔值上调用to_sql

简而言之 – 您需要覆盖ActiveRecord执行方法。 在那里,您可以添加任何记录逻辑。

 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 

积分:

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

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