2015-04-01 43 views
0

我有模型產品(標題,說明,category_id)和類別(標題,說明)。Rails如何在產品模型中按類別製作標籤

class Product < ActiveRecord::Base 
    belongs_to :category 

class Category < ActiveRecord::Base 
    has_many :products 

現在產品只能有一個類別,它的工作完美,但我想打,該產品能有一個更類別,如標籤,但我不能怎麼理解..

+0

請澄清自己,你想你的產品屬於多個類別? – 2015-04-01 13:21:56

回答

0

您需要在has_and_belongs_to_many協會 documented here

編輯:好的,你問簡單的例子

Class Product < ActiveRecord::Base 
    has_and_belongs_to_many :categories 

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :categories 

遷移

create_table :categories do |t| 
    t.string :title 
    ... 

create_table :products do |t| 
    t.string :title 
    ... 

create_table :categories_products, id: false do |t| 
    t.belongs_to :category, index: true 
    t.belongs_to :product, index: true 
end 

您可以用比存取產品類別

Product.find(1).categories