Hi have a products model in my Rails 3.1 app which looked like this:
+----------------+---------------+------+-----+---------+----------------+
| Field
A Product can have multiple Categories, and a Category can refer to multiple Products, right? If so, you want to create a third association table, let's call it product_categories
, and use the standard Rails idioms to support it:
# file: app/models/product.rb
class Product < ActiveRecord::Base
has_many :categories, :through => :product_categories
has_many :product_categories, :dependent => :destroy
end
# file: app/models/category.rb
class Category < ActiveRecord::Base
has_many :products, :through => :product_categories
has_many :product_categories, :dependent => :destroy
end
# file: app/models/product_category.rb
class ProductCategory < ActiveRecord::Base
belongs_to :product
belongs_to :category
end
... and your tables / migrations:
# file: db/migrate/xxx_create_products.rb
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
...
t.timestamps
end
end
end
# file: db/migrate/xxx_create_categories.rb
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.timestamps
end
end
end
# file: db/migrate/xxx_create_product_categories.rb
class CreateProductCategories < ActiveRecord::Migration
def change
create_table :product_categories do |t|
t.references :product
t.references :category
t.timestamps
end
end
end
This way, "adding multiple categories per product" becomes easy:
my_product.categories.create(:name => "toy")
This will create a Category named "toy" as well as the ProductCategory that associates my_product and that new Category. If you want the full description, this Guide is a place to start.