2013-03-17 57 views
1

允許用戶爲他/她創建的產品分配類別的最佳方式是什麼?現在,我通過中介分類模型將產品和類別模型連接起來。通過has_many爲產品指定類別:通過

product.rb

class Product < ActiveRecord::Base 
    attr_accessible :description, :name 

    has_many :categorizations 
    has_many :categories, :through => :categorizations 
end 

category.rb

class Category < ActiveRecord::Base 
    attr_accessible :name 

    has_many :categorizations 
    has_many :products, :through => :categorizations 
end 

categorization.rb

class Categorization < ActiveRecord::Base 
    attr_accessible :category_id, :product_id # Should I leave these accessible? 

    belongs_to :product 
    belongs_to :category 
end 

我UL timately試圖讓它在終端工作爲:

> product = Product.create(name: "Product A", description: "Product A description") 
> Category.create(name: "Cat A") 
> product.categories 
> [] 
> product.categories = "Cat A" 

回答

1

您正在創建一個名爲「貓A」的類別,但你要分配一個字符串「貓A」到product.categories

試試這個:

product.categories.create(:name => "Cat A")