1

我瞭解如何正確設置ActiveRecord的關係,下列情況下一個問題...如何正確設置這些ActiveRecord關係?

現在我有這棵樹的產品:

Product 
-> ProductTypes 
    -> Subtypes 
    -> Subtypes 
     -> ... 
     -> Subtypes 
      -> ProductItem 

,其中產品是:

class Product < ActiveRecord::Base 
    has_many :product_types 
    has_one :product_item, :foreign_key => "product_id" 
end 

產品類型和亞型是:

class ProductType < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :parent_type, :class_name => "ProductType" 
    has_many :subtypes, :class_name => "ProductType", :foreign_key => "parent_type_id" 
    has_one :product_item 
end 

和ProductItem是:

class ProductItem < ActiveRecord::Base 
    belongs_to :product_type 
    belongs_to :product 
end 

但我也想樹允許Product到只有ProductItem(即沒有亞型),如:

Product 
-> ProductItem 

我該如何去設置這些以達到這些要求?謝謝!

回答

0

這取決於ProductType是什麼。如果它是一個分類,那麼可能有has_many:product_types的關聯。如果你真正想要的是實際不同類型的產品,那麼我會用STI讓你的生活變得更簡單。另外,我會簡化product_item到項目,除非你有充分的理由。

http://juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/

STI方式 遷移添加到您的產品表中增加一個類型列:

add_column :products, :type, :string 

然後改變你的模型是這樣的:

product.rb

class Product < ActiveRecord::Base 
    has_one :item 
end 

type_1.rb

class Type1 < Product 
end 

type_2.rb

class Type2 < Product 
end 

爲了您的亞型我會做(以TYPE1爲例)同樣的事情:

subtype_1.rb

class Subtype1 < Type1 
end 

所以,現在所有你不同的類型和子類型有一個與它們相關的項目。您的商品現在只與產品有關聯,而且完成了。

item.rb的

class Item < ActiveRecord::Base 
    belongs_to :product 
end 

如果這不是你想要的話,我會很高興來改變我的回答如果你提供更清晰的內容。

+0

這個答案幫助你一路走來嗎? –