我目前对此很难过。我最近不得不更新我的rails应用程序,现在每当我尝试保存同时尝试保存Visitor对象的对象时,我都会看到此错误弹出窗口。这是失败的代码:
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
我得到的错误是:
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'
起初我以为它可能是Reason.find_by_name,所以我用有效的整数值替换它并且它仍然失败。我能看到的唯一可能失败的代码是routes.rb,它有一个条目:
match 'newsale', :to => 'sales#newsale'
最后,webrick的输出很混乱,因为它实际上显示了保存@sale对象的sql调用,然后我得到以下几行:
SELECT "reasons".* FROM "reasons" WHERE "reasons"."name" = 'Products' LIMIT 1
Completed 500 Internal Server Error in 104ms
答案 0 :(得分:2)
:reason_id => Reason.find_by_name("Products")
此处Rails尝试通过调用Reason
将已找到的:reason_id
实例强制转换为整数值,以设置为Visitor
上的.to_i
属性它(不存在)。
您需要通过更改
告诉Rails id的位置Reason.find_by_name("Products")
到
Reason.find_by_name("Products").id
您也可以在to_i
上定义Reason
方法,并按原样保留您的操作。
alias_method :to_i, :id