Ruby on rails 未定义的方法“to#i';对于#<;原因:0x56f5848>;

Ruby on rails 未定义的方法“to#i';对于#<;原因:0x56f5848>;,ruby-on-rails,Ruby On Rails,我现在在这件事上很困惑。我最近不得不更新我的rails应用程序,现在每当我试图保存一个对象,同时也试图保存一个访问者对象时,就会看到这个错误弹出窗口。以下是失败的代码: if @sale.shift_id.nil? @sale.update_attribute(:shift_id,session[:shift_id]) @title = "New Sale" @sale = Sale.new @pro

我现在在这件事上很困惑。我最近不得不更新我的rails应用程序,现在每当我试图保存一个对象,同时也试图保存一个访问者对象时,就会看到这个错误弹出窗口。以下是失败的代码:

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'
最后,webrick的输出令人困惑,因为它实际上显示了保存@sale对象的sql调用,然后我得到以下几行:

SELECT "reasons".* FROM "reasons" WHERE "reasons"."name" = 'Products' LIMIT 1
Completed 500 Internal Server Error in 104ms

:reason\u id=>reason.find\u by\u name(“Products”)
Rails试图将找到的
reason
实例强制转换为整数值,以设置为
访问者的
:reason\u id
属性,方法是调用
.to\u i
(该实例不存在)

您需要通过更改来告诉Rails id在哪里

Reason.find_by_name("Products")

您也可以在
Reason
上定义
to_i
方法,并保持操作不变

alias_method :to_i, :id

没有骰子。请注意,上面我说过我用一个整数值替换了find_by_name调用,但仍然失败,出现了相同的错误。我怀疑错误是否相同,因为您的原始代码绝对有问题。我甚至不确定它以前是如何工作的。看起来我有一个git错误,它没有推送固定的文件,所以现在它的id有了固定。我只是不明白为什么它以前有效,而不是现在。。。
Reason.find_by_name("Products").id
alias_method :to_i, :id