sql - (子)类别的表和 Ruby ActiveRecord 类设计

标签 sql ruby-on-rails ruby database activerecord

我想我有一个相当简单的问题,因为我是 Ruby 的新手,甚至是 ActiveRecords 的新手。

我想要实现的是使用 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 吗?类(class)会是什么样子?我只是想不通 JoinTable 如何适应 ActiveRecord 结构。

此外,我如何为来自 parent_id->categories.id 的链接建模?

感谢任何帮助!

干杯

最佳答案

要对您描述的关系建模,您会做:

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 中消失了

为了获取信息,我经常使用控制台 rails console 进行测试,这将允许你这样做

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

链接的遍历是通过您在模型中设置的关系进行的,目的是在使用合理名称的上下文中使其可读。根据您的问题,自连接也包含在 Rails Guides: Associations 中。有一个很好的例子。本指南的其余部分还详细介绍了其他关系。

要记住的另一件事是创建迁移,以便使用作为外键的 ID 创建连接表。

关于sql - (子)类别的表和 Ruby ActiveRecord 类设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7198045/

相关文章:

mysql - 如何进行正确的加盟?

mysql - 查找至少参与过两个项目的所有员工

SQL - 选择值等于多个值的项目

ruby-on-rails - 如何教 Rails 表单按钮提交使用远程?

sql - Rails 4 JOIN GROUP BY 和 SELECT

ruby-on-rails - Rails - 在 Devise 中禁用 "already_authenticated"重定向

.net - 哪种 Ruby 实现会存活下来?

ruby-on-rails - 如何在 Rails 上获取 ruby​​ 类名和字段名

java - HQL SELECT 子句不起作用

sql - 如何更新 Rails 中的序列并在我的对象中获取结果值?