3個多小時,我想解決很容易錯誤(在第一眼):Ruby - 未定義的方法`空?'對於零:NilClass
undefined method `empty?' for nil:NilClass
,但仍然沒有成功。
我有DB表products
,其中包含列category_id
和manufacturer_id
。
協會:
class Product < ActiveRecord::Base
belongs_to :manufacturer
belongs_to :category
...
end
class Category < ActiveRecord::Base # the same for Manufacturer
has_ancestry
has_many :products
end
試圖抓住一些數據:
Product.where('category_id IS NOT NULL AND manufacturer_id IS NOT NULL').each do |product|
...
puts product.manufacturer.name # here's the error
puts product.category.name # here's the error
...
end
我拿來的所有行,這裏是不是在列manufacturer_id
和category_id
NIL值...所以我怎樣才能這個錯誤?
而且,我已經試過:
...
puts product.manufacturer.name unless product.manufacturer_id.nil?
puts product.category.name unless product.category_id.nil?
...
我在做什麼錯?
您沒有提及發生錯誤的行。 –
這個'放product.manufacturer.name'或這個:'放product.category.name',我只提到有問題的。 – user984621
未定義的方法'空?'對於你在問題中提到的nil:NilClass。那**空**相關線路在哪裏。 – Santosh