1

允许用户将类别分配给他/他创建的产品的最佳方式是什么?现在,我通过中间分类模型连接了产品和类别模型。

产品.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"
4

1 回答 1

1

您正在创建一个名称为“Cat A”的类别,但随后您将字符串“Cat A”分配给 product.categories

尝试这个:

product.categories.create(:name => "Cat A")
于 2013-03-17T01:49:49.480 回答