允许用户将类别分配给他/他创建的产品的最佳方式是什么?现在,我通过中间分类模型连接了产品和类别模型。
产品.rb
class Product < ActiveRecord::Base
attr_accessible :description, :name
has_many :categorizations
has_many :categories, :through => :categorizations
end
类别.rb
class Category < ActiveRecord::Base
attr_accessible :name
has_many :categorizations
has_many :products, :through => :categorizations
end
分类.rb
class Categorization < ActiveRecord::Base
attr_accessible :category_id, :product_id # Should I leave these accessible?
belongs_to :product
belongs_to :category
end
我最终试图让它在终端中工作:
> product = Product.create(name: "Product A", description: "Product A description")
> Category.create(name: "Cat A")
> product.categories
> []
> product.categories = "Cat A"