I am currently pretty stumped on this one. I recently had to update my rails application and now am seeing this error popup whenever I try to save an object that also tries to save a Visitor object. Here is the code that is failing:
if @sale.shift_id.nil?
@sale.update_attribute(:shift_id,session[:shift_id])
@title = "New Sale"
@sale = Sale.new
@products = Product.order("name")
@shifts = Shift.order("starttime")
#this line below is line 51, which the output says is the failing line.
Visitor.new(:gender => 'Other', :shift_id => session[:current_shift_id], :reason_id => Reason.find_by_name("Products")).save
redirect_to(newsale_path, :notice => 'successfully added the sale')
else
The error I get is:
undefined method `to_i' for #<Reason:0x56f5848>
Rails.root:
Application Trace | Framework Trace | Full Trace
app/controllers/sales_controller.rb:51:in `new'
app/controllers/sales_controller.rb:51:in `create'
At first I thought it might be the Reason.find_by_name, so I replaced that with a valid integer value and it still failed. The only other bit of code that I can see that might fail is the routes.rb, which has an entry under:
match 'newsale', :to => 'sales#newsale'
Lastly, the output to the webrick is confusing because it actually shows the sql calls saving the @sale object, and then I get the following lines:
SELECT "reasons".* FROM "reasons" WHERE "reasons"."name" = 'Products' LIMIT 1
Completed 500 Internal Server Error in 104ms
:reason_id => Reason.find_by_name("Products")here Rails is trying to cast the foundReasoninstance to an integer value to set as the:reason_idattribute onVisitorby calling.to_ion it (which doesn’t exist).You need to tell Rails where the id is by changing
to
You can alternatively define a
to_imethod onReasonand leave your action as-is.