product.rb
class Product < ActiveRecord::Base
attr_accessible :description, :name
has_many :categorizations
has_many :categories, :through => :categorizations
validates :name, uniqueness: true
end
category.rb
class Category < ActiveRecord::Base
attr_accessible :name
has_many :categorizations
has_many :products, :through => :categorizations
validates :name, uniqueness: true
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
这就是我在终端尝试的内容:
> p1 = Product.create(name: "Product A", description: "Product A description")
> p1.categories
> []
> Category.all
> []
> p1.categories.create(:name => "Cat A")
> p1.categories.find(1).name
> ["Cat A"]
>
> p2 = Product.create(name: "Product B", description: "Product B description")
> p2.categories
> []
> p2.categories.update_attributes(:name => "Cat A")
我得到'update_attributes'的未定义方法错误。
答案 0 :(得分:0)
我希望您的类别名称属性是唯一的。
@categoryCatA = Category.find_by_name("Cat A")
p1.categories << @categoryCatA
p2.categories << @categoryCatA
要获取分配给某个产品的所有类别的名称,这将返回一个数组:
p1.categories.map {|category| category.name}
答案 1 :(得分:0)
对于任何好奇的人,我在一篇写得很好的文章中找到了答案:
http://tutorials.jumpstartlab.com/projects/blogger.html#i3:-tagging