2011-08-25 57 views
1

我想我有一個相當簡單的問題,因爲我是Ruby新手,甚至更新的ActiveRecords。表和Ruby ActiveRecord類設計(子)類

我想實現的是與ActiveRecords一類表示(以及相應的SQL模式),該模型的以下問題:

  • 存在着分類和子類(由PARENT_ID建模)
  • 產品屬於只有一類
  • 每件產品可以0..inf功能
  • 特點只是有一些數據字段,僅由產品引用

我目前的架構如下所示的圖片: My database schema for representing products belonging to sub(categories). Each product has a certain number of Features.

是這個模式適合ActiveRecords?這些課程會是怎樣的?我只是不知道JoinTable如何適應ActiveRecord結構。

此外,我如何建立從parent_id->categories.id鏈接?

任何幫助表示讚賞!

歡呼

回答

1

爲了模擬你描述你會做的關係:

models/category.rb 
class Category < ActiveRecord::Base 
    has_many :products 
    has_many :subcategories, :class_name => "Category", :foreign_key => :parent_id 
end 

models/product.rb 
class Product < ActiveRecord::Base 
    belongs_to :product 
    has_many :features, :through => :product_features 
    has_many :product_features 
end 

models/feature.rb 
class Feature < ActiveRecord::Base 
    has_many :product_features 
    has_many :products, :through => :product_features 
end 

models/productfeature.rb 
class ProductFeature < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :feature 
end 

鑑於這種結構,那麼你的聯接建模爲一個多到很多關係。這是有用的,因爲HABTM連接風格在Rails 3中消失了。1

來獲取信息,我經常使用控制檯軌控制檯進行測試,這將讓你做

@category = Category.first #get the first category 
@category.subcategories  #returns an array of categories 

鏈接的遍歷是通過關係,您在模型建立目的是在使用明智的名稱的情況下其可讀。根據您的問題,自我加入也包含在Rails Guides: Associations中,並有一個很好的例子。本指南的其餘部分還詳細介紹了其他關係。

要記住的另一件事是創建您的遷移,以便使用外鍵的id創建連接表。

+0

謝謝,很好的答案。已經Upvoted。 – pokey909

+0

由於最完整的答案我選擇你的最好的。這讓我走上了正軌,我想我現在已經掌握了一些。 類別仍然缺少'belongs_to:parant_category,:class_name =>「Category」'以允許上下遍歷。但除此之外,一切似乎都是正確的。 再次感謝! – pokey909

0

這裏是ActiveRecord::Associations::ClassMethods

的API裏面還有不同的關係,以及如何構建他們很多的例子。值得花時間瞭解如何/爲什麼要構建這些關聯。

對於許多一對多聯接,你會想看看

  • has_many ..., :through => ...
  • has_and_belongs_to_many ...

的文檔說明何時以及爲什麼使用每個。

+0

謝謝,現在你的答案包含實際信息:-) 據我現在看到它,這意味着我不必模擬連接表的模型。 但映射器如何知道我的連接表的名稱? 我可以指定它嗎? – pokey909

+0

如果您閱讀API文檔,會有很多關於名稱的推斷(請記住,rails是'convention over configuration')。這就是爲什麼當你開始這種工作可能會讓你感到沮喪 - 我最近一直在努力與自我參考許多聯繫 –

1

我的模式是這樣的:

class Category < ActiveRecord::Base 
    has_many :products 
end 

class Product < ActiveRecord::Base 
    belongs_to :category 
    has_many :product_features 
    has_many :features, :through => :product_features 
end 

class ProductFeature < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :feature 
end 

class Feature < ActiveRecord::Base 
    has_many :product_features 
    has_many :products, :through => :product_features 
end 

Rails有關聯叫has_and_belongs_to_many。 Rails希望有一個包含兩列的表來存儲連接數據。我通常使用雙has_many來獲得相同的結果,因爲它可以靈活地在連接表中添加附加信息。

示例代碼

product.category 
product.category = category1 


category.products 
category.products << product1 


product.features 
product.features << feature1 

feature.products 
feature.products << product1 
+0

感謝您的廣泛信息。這正是我所期待的。當我仔細閱讀你的和格蘭特的優秀答案時,我很快就會接受答案。 – pokey909