Matt Elhotiby
Matt Elhotiby

Reputation: 44076

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

Upvotes: 1

Views: 44

Answers (1)

Dave Pirotte
Dave Pirotte

Reputation: 3816

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

Upvotes: 3

Related Questions