2010-08-29 46 views
1

我需要有一个许多人对产品和类别进行连接需要

,所以我有

class Category < ActiveRecord::Base 
    has_many :categorizations 
    has_many :products, :through => :categorizations 
end 

class Product < ActiveRecord::Base 
    has_many :categorizations 
    has_many :categories, :through => :categorizations 
end 

一对多的关系分类已的结构是这样的

* PRODUCT_ID (primary key, foreign key to PRODUCTS) 
* CATEGORY_ID (primary key, foreign key to CATEGORIES) 
* QUANTITY 
在我的控制器

我正在创建此类别和产品

@new_product = Product.create :name => "test" 
@new_category = Category.create :name => "test category" 

如何连接这两个,我如何设置数量

与一对多如果我的记忆正确地为我服务,这是如何完成的。但随着多对多通过我失去了

@ new_product.catagory < < @new_category

回答

3

当你有一个多对多关联有元数据(即经历过多次),你应该创建关联对象明确。

@new_product = Product.create(:name => "test") 
@new_category = Category.create(:name => "test category") 
@association = Categorization.create(:product => @new_product, :category => @new_category, :quantity => 5) 

你没有显示此之上,但要记住,你需要创建一个模型为您的协会与的has_many使用它:通过。

class Categorization < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :category 
end 
相关问题