2012-11-14 25 views
0

3個多小時,我想解決很容易錯誤(在第一眼):Ruby - 未定義的方法`空?'對於零:NilClass

undefined method `empty?' for nil:NilClass 

,但仍然沒有成功。

我有DB表products,其中包含列category_idmanufacturer_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_idcategory_id NIL值...所以我怎樣才能這個錯誤?

而且,我已經試過:

... 
    puts product.manufacturer.name unless product.manufacturer_id.nil? 
    puts product.category.name unless product.category_id.nil? 
    ... 

我在做什麼錯?

+1

您沒有提及發生錯誤的行。 –

+0

這個'放product.manufacturer.name'或這個:'放product.category.name',我只提到有問題的。 – user984621

+1

未定義的方法'空?'對於你在問題中提到的nil:NilClass。那**空**相關線路在哪裏。 – Santosh

回答

1

您很可能會刪除製造商或類別,因此沒有相應的記錄來匹配外鍵。

0

考慮到您的查詢,可能是數據庫上的業務邏輯問題。

恕我直言,你正在調用一些不會有效的對象。檢查你的數據庫,看看所有寄存器是否都出現你的驗證邏輯。

相關問題