2013-03-17 66 views
0

product.rb的has_many:通過 - 匹配現有的產品類別,否則創建新的產品類別

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方法」。

  1. 如何將產品分配到某個類別而不在數據庫中創建重複的類別? (即由於上面已經創建了「貓A」,我如何將「p2」分配給同一類別,同時只保留數據庫中的「貓A」的一條記錄?)
  2. 當我想要搜索特定產品的類別,當我輸入「p.categories.name」時,我找回模型「類別」的名稱。我怎樣才能獲得數組中的類別名稱?
  3. 什麼是最好的方式來實現這個在網絡表單?

回答

0

我希望您的類別名稱屬性是唯一的。

@categoryCatA = Category.find_by_name("Cat A") 

p1.categories << @categoryCatA 

p2.categories << @categoryCatA 

要獲得分配給某一個產品的所有類別的名稱,這將返回一個數組:

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