允许用户为他/她创建的产品分配类别的最佳方法是什么?现在我通过中间分类模型连接了产品和类别模型。
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
我最终试图让它在终端中工作:
> product = Product.create(name: "Product A", description: "Product A description")
> Category.create(name: "Cat A")
> product.categories
> []
> product.categories = "Cat A"
答案 0 :(得分:1)
您正在创建一个名为“Cat A”的类别,但是您要为product.categories分配字符串“Cat A”
试试这个:
product.categories.create(:name => "Cat A")