【问题标题】:how to remove this error : undefined method `inc' for nil:NilClass如何消除此错误:nil:NilClass 的未定义方法“inc”
【发布时间】:2015-04-09 19:58:29
【问题描述】:

我在您的浏览器中写了“http://localhost:3000/items/create?name=car1&description=good+car&price=500000&weight=0&real=1”,出现错误

nil:NilClass 的未定义方法 `inc'

提取的源代码(第 11 行附近):

9 after_initialize { puts 'initialize' } 
10 after_save { puts 'saved' } 
11 after_create { category.inc(:items_count, 1) }  
12 after_update { puts 'updated' } 
13 after_destroy { category.inc(:items_count, -1) } 
14

Rails.root: E:/work/my_store

应用程序跟踪 |框架跟踪 |完整跟踪

app/models/item.rb:11:in `block in <class:Item>'
app/controllers/items_controller.rb:9:in `create'

请求

参数:

{"name"=>"car1",
 "description"=>"good car",
 "price"=>"500000",
 "weight"=>"0",
 "real"=>"1"}

【问题讨论】:

  • 这简直是在告诉您您正在对 nil 对象调用方法 inc。在您的代码中,您使用category.inc(some_args),然后category 等于nil。请改用self.incself 引用您正在执行代码的上下文,或使用after_create { |category| category.inc(:items_count, 1) }

标签: ruby-on-rails


【解决方案1】:

在第 11 行中,您正在执行 category.inc(:items_count, 1) 所以这意味着该类别目前为零。我没有看到控制器代码,所以我的猜测是您还没有创建类别,或者没有将 category 变量设置为正确的值。实际上通常不需要做类似的事情

   category.inc(:items_count, 1)

因为如果一切设置正确,您总是可以这样做

   category.items.count

计算类别中的所有项目。

您是否尝试完成任何教程?我推荐Michael Hartl's tutorial。这很简单,但你可以从中学到相当复杂的东西。

【讨论】:

  • 对不起,我只是在学习,您可能会感到困惑,但感谢您的理解。我明白错误在哪里
猜你喜欢
  • 1970-01-01
  • 2012-12-27
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
相关资源
最近更新 更多