2010-12-02 60 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中。很可能是因爲每次在開發環境中重新加載類。這個代碼只需要執行一次。

相關問題