rails has_many:通过NameError

时间:2012-10-04 10:48:34

标签: ruby-on-rails-3 has-many-through

我有以下设置

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

在rails控制台中,我尝试使用以下命令分配category_ids p.category_ids = [1,2](其中p = Product.first)我得到

NameError: uninitialized constant Product::CategoryProduct

任何建议?

感谢

2 个答案:

答案 0 :(得分:0)

事实证明,rails不喜欢加入模型的“多”名称,创建了一个名为分类的新模型,并且所有工作都是100%

答案 1 :(得分: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(没有 s ),而且表格 categories_products

相关问题