2010-12-02 58 views
2

这个问题是跟在question之后的,我应该在哪里放置这段代码?在Rails 3中记录每个SQL查询到数据库

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查询,曾多次返回“栈层次是深”的错误。

回答

2

把它放在config/initializers中。很可能是因为每次在开发环境中重新加载类。这个代码只需要执行一次。

相关问题