2012-10-24 56 views
1

精細控制器相關的代碼如下:的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修復了問題

+0

請向我們展示500錯誤 – agmin

+0

我在控制器代碼和軌道控制檯中看到的唯一區別是記錄器的用法。你不記錄rails控制檯的情況,並且初始化@cost。你有沒有嘗試從控制器註釋掉日誌報告,並檢查你是否得到500? – Raghu

+0

我建議開挖記錄器並使用ruby-debug。它會保存你的理智。閱讀第3部分:http://guides.rubyonrails.org/debugging_rails_applications.html –

回答

1

試試看

if params.has_key?(:special_edition) && params[:special_edition] == "yes" 

如果錯誤仍然存​​在,只是檢查是否@cost是通過分配一個值,或與to_i方法的整數。

2

顯式@成本初始化的區別。 在您的控制器操作開始時寫@cost = 350000

+0

請參閱編輯我的文章。 @cost正在初始化代碼 – EastsideDeveloper

+0

好吧。試試這個\ @cost = \ @ cost.to_i + 50000 – 907th

+0

我不知道怎麼寫\ @ eithout \ =) – 907th

相關問題