making the connection needed
I need to have a many to many relationship开发者_如何转开发 for products and categories
so i have
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
the structure of categorizations is this
* PRODUCT_ID (primary key, foreign key to PRODUCTS)
* CATEGORY_ID (primary key, foreign key to CATEGORIES)
* QUANTITY
in my controller i am creating the category and product by this
@new_product = Product.create :name => "test"
@new_category = Category.create :name => "test category"
how do I connect these two and how do i set the quantity
with one to many if my memory serves me correctly this is how its done. But with the many to many through i am lost
@new_product.catagory << @new_category
When you have a many to many association that has metadata (i.e. has many through), you should create the association object explicitly.
@new_product = Product.create(:name => "test")
@new_category = Category.create(:name => "test category")
@association = Categorization.create(:product => @new_product, :category => @new_category, :quantity => 5)
You didn't show this above, but remember that you need to create a model for your association to use it with has_many :through.
class Categorization < ActiveRecord::Base
belongs_to :product
belongs_to :category
end
精彩评论