(抱歉英语不好)
假设我有模型 A、B、C。每个模型都有一个地址。
在“SQL 反模式:避免数据库编程的陷阱”(第 7 章 - 多态关联)一书中,有一个方法可以通过使用“通用超级表”(也称为基表或祖先表)来避免这种关联。
在多态上,它将是:
table addresses:
id: integer
parent_type:string # 'A', 'B' or 'C'
parent_id: integer
我知道您可以使用交集表,但以下解决方案看起来更精致:
配方建议创建一个只有一个 id 字段(代理键或伪键)的超级表(寻址),而不是多态地将 A、B、C 与地址相关联。然后,其他表引用寻址。这样,作者说,“您可以依靠外键强制执行数据库的数据完整性”。所以,它会是:
table addressing
id: integer
table addresses
id: integer
addressing_id: integer (foreign_key)
zip: string
table a
id: integer
addressing_id: integer (foreign_key)
name: string
table b
id: integer
addressing_id: integer (foreign_key)
name: string
table c
id: integer
addressing_id: integer (foreign_key)
name: string
SQL 查询将如下所示:
SELECT * from a
JOIN address USING addressing_id
WHERE a.addressing_id = 1243
问题是:如何在 Rails 中编写这样的场景?我尝试了几种方法都没有成功。