这个问题是对此question的跟进,我应该在哪里放置此代码?
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
我已经尝试将它放在模型中,但是当我执行一些sql查询时,一旦它返回“堆栈级别为深”错误,会发生什么。
答案 0 :(得分:2)
将它放在config / initializers中。很可能是因为每次在dev环境中重新加载类。这段代码只需要执行一次。