The relevant piece of code in the controller is the following:
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)
When I run the app, I get a 500 error. Checking into the log file (test log file), I see the following:
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
If I enter the console (rails console), and run this code (values taken from the log file:
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
Then I get the correct result for @cost: 415000
Any ideas why I might be getting a 500 error?
Clarification:
Several responses mentioned that the difference is that the difference is that I’m initializing @cost but not doing it in the controller. The code that’s initializing @cost is not included, because it is already initializing properly. I included the piece of code that logs @cost to the log file and I am initializing it in the console using the value I am getting for @cost from the log file (see my code, lines 3 & 4 and then the output from the log file lines 3 & 4)
I tried to use the comment feature, but stackoverlfow is giving me an error message.
Resolution
It turns out that another module in the app was reading the interget @cost and turning it into a string. This was masked by another bug in the app, so an earlier test failed. Moral of the story: regression testing is essential. Using @cost.to_i fixed the problem
Just try
if the error persists, just check if the @cost is an integer by assigning a value or with the to_i method.