has_many:通过匹配现有的产品类别,否则创建新的产品类别

  • 本文关键字:创建 many has ruby-on-rails
  • 更新时间 :
  • 英文 :


产品.rb

class Product < ActiveRecord::Base
  attr_accessible :description, :name
  has_many :categorizations
  has_many :categories, :through => :categorizations
  validates :name, uniqueness: true
end

类别.rb

class Category < ActiveRecord::Base
  attr_accessible :name
  has_many :categorizations
  has_many :products, :through => :categorizations
  validates :name, uniqueness: true
end

分类.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"出现未定义的方法错误。

  1. 如何在不在数据库中创建重复类别的情况下将产品分配给类别?(即,由于上面已经创建了"Cat A",我如何将"p2"分配为具有相同的类别,同时在数据库中只保留一条"Cat A"记录?(
  2. 当我想搜索特定产品的类别时,当我键入"p.categories.name"时,我会返回型号的名称"Category"。如何在数组中重新获取类别名称
  3. 在web表单中实现此功能的最佳方式是什么

我希望您的类别名称属性是唯一的。

@categoryCatA = Category.find_by_name("Cat A")
p1.categories << @categoryCatA
p2.categories << @categoryCatA

要获取分配给某个产品的所有类别的名称,这将返回一个数组:

p1.categories.map {|category| category.name}

对于任何好奇的人来说,我在一篇写得很好的文章中找到了答案:

http://tutorials.jumpstartlab.com/projects/blogger.html#i3:-标记

最新更新