我有一张
tenants
的桌子。虽然 tenants
确实有一个 id
,但它们还有一个 code
列,该列是唯一的并且也有索引。 code
列值的优点是人类可读。因此,我想在对其他各种表创建外键约束时使用它。然而,到目前为止,我还没有在谷歌上搜索如何实现这一点。
例如,我在迁移中尝试了以下操作来添加新表:
class CreateApps < ActiveRecord::Migration[7.1]
def change
create_table :apps, id: :uuid do |t|
...
t.references :tenant_code, type: :string, index: true, foreign_key: { to_table: :tenants }
...
end
end
end
不幸的是,当我尝试运行此迁移时,我收到如下错误:
PG::DatatypeMismatch:错误:无法实现外键约束“fk_rails_899289dfd2”详细信息:键列“tenant_code_id”和“id”的类型不兼容:字符变化和uuid。
Rails 希望将
_id
附加到我在此处指定的任何列名称,而不仅仅是使用 tenant_code
,并且它尝试将其链接到 tenants
表的 id
列而不是 code
列...
如何让 Rails 创建带有
apps
列的 tenant_code
表,并通过其 tenants
列作为 code
表的外键?
使用 列选项 设置目标表上的列。默认值是您收集的
to_table.singularize + "_id"
。
t.references :tenant_code,
type: :string,
index: true,
foreign_key: { to_table: :tenants, column: :code }