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<
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
These methods both return a boolean. You can't invoke to_sql
on a boolean.