首页 > 解决方案 > 具有不同主键的 HABTM 连接表

问题描述

我有两种型号1.category主键是cust_number,2.product主键是id。现在我想在类别和产品之间建立一个 HABTM 关系。这里的问题是如何创建以 cust_number 和 product_id 为键的连接表?

标签: ruby-on-rails

解决方案


对于这个用例,您想使用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 

推荐阅读