ruby-on-rails - 具有不同主键的 HABTM 连接表
问题描述
我有两种型号1.category
主键是cust_number
,2.product
主键是id
。现在我想在类别和产品之间建立一个 HABTM 关系。这里的问题是如何创建以 cust_number 和 product_id 为键的连接表?
解决方案
对于这个用例,您想使用has_many through:
而不是has_and_belongs_to_many
. 他们都实现了相同的目标(m2m 关联),但has_and_belongs_to_many
非常有限。
AFAIK HABTM 仅采用用于在连接表上设置外键的foreign_key
选项,似乎没有办法告诉它 FK 指向什么 PK。
运行生成器以创建连接模型:
rails g model category_product product:references
打开迁移并更改外键,使其指向您的自定义主键:
create_table :category_products do |t|
t.references :product, foreign_key: true
t.references :category, foreign_key: { primary_key: "cust_number" }
end
更改关联中的外键:
class CategoryProduct < ApplicationRecord
belongs_to :category, foreign_key: "cust_number"
belongs_to :product
end
然后将has_many through:
关联添加到每一端:
class Category < ApplicationRecord
has_many :category_products
has_many :products, through: :category_products
end
class Product < ApplicationRecord
has_many :category_products
has_many :categories, through: :category_products
end
推荐阅读
- javascript - 是否可以在 CytoscapeJS 中只为图形的一个节点着色?
- java - 可以使用 FloatingActionButton 而不挥之不去吗?
- excel - 尝试使用 VBA 输入日期时出错
- swift - 如何使用 GCD 从 DispatchQueue.concurrentPerform() 聚合数据?
- python - 在 pandas 中添加唯一值的串联作为 groupby 输出
- android - 以编程方式发送蓝牙广告包
- c# - 在 BackgroundWorker 的 RunWorkerCompleted 中运行 Async/Await 任务
- r - 直方图如何将 y 轴从计数更改为频率并跨两个数据集进行标准化
- python - 对 Generic 类的子类使用不同的 TypeVar
- python - 随机游走(Python 速成课程)陷入似乎是一个循环的状态