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