![](/img/trans.png)
[英]How to catch “error”:“undefined method `[]' for nil:NilClass”
[英]how to remove this error : undefined method `inc' for nil:NilClass
我在您的瀏覽器中寫道“ 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"}
在第11行中,您正在進行category.inc(:items_count, 1)
因此這意味着類別目前為零。 我沒有看到控制器代碼,所以我的猜測是您要么尚未創建類別,要么未將category
變量設置為適當的值。 實際上,通常不需要做類似的事情
category.inc(:items_count, 1)
因為如果一切設置正確,您總是可以
category.items.count
計算類別中的所有項目。
您是否嘗試完成任何教程? 我推薦Michael Hartl的教程 。 它很簡單,但是您可以從中學習非常復雜的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.