未定义的方法`name'为零:NilClass与红宝石2.2.2

时间:2015-08-18 12:39:33

标签: ruby-on-rails ruby

我有两个has_and_belongs_to_many关系的课程。

当我试图摧毁一个物体时,我得到了:

> undefined method `name' for nil:NilClass error.

我使用的是Ruby 2.2.2。相同的代码适用于Ruby 2.1.2。

我的控制器代码:

@cart = Cart.find(1)
@cart.temp_orders.find(4).destroy

我的模特:

class Cart < ActiveRecord::Base
  has_many :temp_orders
end

class TempOrder < ActiveRecord::Base
  belongs_to :cart
  has_and_belongs_to_many :kids, join_table: :kid_temp_orders
end

class Kid < ActiveRecord::Base
  has_and_belongs_to_many :temp_orders
end

堆栈追踪:

> NoMethodError (undefined method `name' for nil:NilClass):   app/controllers/carts_controller.rb:50:in `destroy'
>  Rendered /home/dell/.rvm/gems/ruby-2.2.1/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (5.8ms)
>  Rendered /home/dell/.rvm/gems/ruby-2.2.1/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (29.3ms)
>  Rendered /home/dell/.rvm/gems/ruby-2.2.1/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (10.7ms
>  Rendered /home/dell/.rvm/gems/ruby-2.2.1/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (123.5ms

2 个答案:

答案 0 :(得分:4)

OP确实无法发布此错误的任何其他数据。我认为OP在这种情况下不值得那些投票。

这是ActiveRecord和Ruby 2.2的问题

您可以通过将ruby版本从ruby-2.2.0切换到ruby-2.1.2 / ruby​​-2.1.3或者将版本从4.0.0切换到4.1.2来修复它

选中此SO link

答案 1 :(得分:0)

升级:

ruby '2.3.0'
gem 'rails', '4.1.1'

为:

ruby '2.3.0'    
gem 'rails', '4.1.16'

为我做了伎俩