2011-08-25 58 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