为了模拟你描述你会做的关系:
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