2012-10-04 130 views
0

我具有以下設置導軌的has_many:通過NameError

class Category < ActiveRecord::Base 

has_many :category_products 
has_many :products, through: :category_products 

end 

class Product < ActiveRecord::Base 

has_many :category_products 
has_many :categories, through: :category_products 

end 

class CategoryProducts < ActiveRecord::Base 
belongs_to :category 
belongs_to :product 
end 

在導軌控制檯I嘗試使用以下命令 p.category_ids =分配category_ids [1,2](其中p = Product.first)予得到

NameError: uninitialized constant Product::CategoryProduct 

有什麼建議嗎?

感謝

+0

原來,護欄沒有爲加盟模式類似「多」的名字,創造了一個新的模式稱爲分類和所有作品100% –

回答

0

您只需打一個錯字。試試這個:

class Category < ActiveRecord::Base 
    has_many :categories_products 
    has_many :products, through: :categories_products 
end 

class Product < ActiveRecord::Base 
    has_many :categories_products 
    has_many :categories, through: :categories_products 
end 

class CategoriesProduct < ActiveRecord::Base # singular association model define 
    belongs_to :category 
    belongs_to :product 
end 

注意關聯名稱。

模式categories_product(無小號),這是categories_products

0

證明,軌道不喜歡的加入模型中的「多」的名字,創造了一個新的模式稱爲分類和一切工作100%