精細控制器相關的代碼如下:的Rails:應用程序失敗,但代碼運行在控制檯
logger.info("Dumping params")
logger.info(params)
logger.info("Dumping initial cost:")
logger.info(@cost)
logger.info("entering if statement")
if params.has_key?("special_edition") && params["special_edition"] == 'yes'
@cost = @cost + 50000
end
logger.info("If we get to here then the first conditional executed correctly")
if params.has_key?("number_of_lids") && params["number_of_lids"].to_i > 0
@cost = @cost + (params["number_of_lids"].to_i * 5000)
end
logger.info("If we get to here then the second conditional executed correctly")
logger.info("printing final cost:")
logger.info(@cost)
當我運行應用程序,我得到一個500錯誤。檢查到日誌文件(測試日誌文件),我看到以下內容:
Dumping params
{"utf8"=>"✓", "special_edition"=>"yes", "number_of_lids"=>"3", "action"=>"create"}
Dumping initial cost:
350000
entering if statement
Completed 500 Internal Server Error in 1922ms
如果我進入控制檯(軌控制檯),並運行此代碼(從日誌文件中獲取值:
params = {"utf8"=>"✓", "special_edition"=>"yes", "number_of_lids"=>"3", "action"=>"create"}
@cost = 350000
if params.has_key?("special_edition") && params["special_edition"] == 'yes'
@cost = @cost + 50000
end
if params.has_key?("number_of_lids") && params["number_of_lids"].to_i > 0
@cost = @cost + (params["number_of_lids"].to_i * 5000)
end
然後我得到@cost正確的結果:415000個
任何想法,爲什麼我可能會得到一個500錯誤
澄清:
幾個回覆提到,不同之處在於,我在初始化@cost但不在控制器中執行它。不包含初始化@cost的代碼,因爲它已正確初始化。我在日誌文件中包含了將@cost日誌記錄到日誌文件中的一段代碼,並使用我從日誌文件中獲得的@cost值在控制檯中初始化它(請參閱我的代碼,第3行,第& 4行,然後從第日誌文件行3 & 4)
我試圖使用評論功能,但stackoverlfow給我一個錯誤消息。
分辨率
事實證明,在應用程序的另一個模塊正在讀interget @cost,並把它變成一個字符串。這被應用程序中的另一個bug掩蓋了,所以較早的測試失敗了。故事的道德:迴歸測試是至關重要的。使用@ cost.to_i修復了問題
請向我們展示500錯誤 – agmin
我在控制器代碼和軌道控制檯中看到的唯一區別是記錄器的用法。你不記錄rails控制檯的情況,並且初始化@cost。你有沒有嘗試從控制器註釋掉日誌報告,並檢查你是否得到500? – Raghu
我建議開挖記錄器並使用ruby-debug。它會保存你的理智。閱讀第3部分:http://guides.rubyonrails.org/debugging_rails_applications.html –