爲了模擬你描述你會做的關係:
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創建連接表。
謝謝,很好的答案。已經Upvoted。 – pokey909
由於最完整的答案我選擇你的最好的。這讓我走上了正軌,我想我現在已經掌握了一些。 類別仍然缺少'belongs_to:parant_category,:class_name =>「Category」'以允許上下遍歷。但除此之外,一切似乎都是正確的。 再次感謝! – pokey909