2012-01-15 61 views
2

我已經記住以下幾點:Rails的分層模型 - 多個類別

  1. 一個產品可以有多個類別
  2. 一個類可以在不同的產品。
  3. 一個有父(類別),如果它不是一個普通類(在這種情況下,父母將無)

從一個關係型數據庫一點想,這會是這樣,我將實施爲:

  1. 產物
  2. PRODUCT_CATEGORY(作爲主鍵:PRODUCT_ID,CATEGORY_ID)
  3. (帶PARENT_ID引用類別或零,如果這是一個「普通」 cateogry)

從一個Rails的造型上看思考,我有以下的(我避免寫字段沒有真正的問題此關係/分層問題我處理):

class Product < ActiveRecord::Base 
... 
has_many :categories 


class Category < ActiveRecord::Base 
... 
Here comes de doubt: How do I specify the parent_id? 

有什麼方法來指定一個類別都有一個,只是一個父ID其另一類別的參考?

回答

6

像這樣的東西是相當典型:

class Product < ActiveRecord::Base 
    has_many :categories, :through => :products_categories 

    # A has_and_belongs_to_many association would also be fine here if you 
    # don't need to assign attributes to or perform any operations on the 
    # relationship record itself. 
end 

class Category < ActiveRecord::Base 
    has_many :products, :through => :products_categories 

    belongs_to :category 
    has_many :categories # Optional; useful if this is a parent and you want 
end      # to be able to list its children. 

或者你可以給這最後兩個不同的名字,例如:

belongs_to :parent, :class_name => :category 
has_many :children, :class_name => :category