开发者

making the connection needed

开发者 https://www.devze.com 2023-01-14 14:06 出处:网络
I need to have a many to many relationship开发者_如何转开发 for products and categories so i have

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号