You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ruby on Rails中设置Transactions引用Accounts的account_id外键

在Ruby on Rails中设置外键引用非主键字段

要让Transactions表的account_id字段引用Accounts表的account_id(非主键),需要修改迁移文件并调整模型关联配置:

1. 修改迁移文件

默认情况下add_foreign_key会引用关联表的主键(id),你需要通过primary_key参数显式指定要引用的字段:

class AddForeignKeyToTransactions < ActiveRecord::Migration[7.1]
  def change
    add_foreign_key "transactions", "accounts", 
      column: :account_id, 
      primary_key: :account_id
  end
end

如果之前已经执行过原迁移,需要先回滚再重新执行:

rails db:rollback
rails db:migrate

或者创建新的迁移来修改外键约束:

class UpdateTransactionForeignKey < ActiveRecord::Migration[7.1]
  def change
    remove_foreign_key "transactions", "accounts"
    add_foreign_key "transactions", "accounts", 
      column: :account_id, 
      primary_key: :account_id
  end
end

2. 调整模型关联配置

现有模型关联缺少primary_key指定,会导致ActiveRecord查询时仍用主键id关联,需要补充:

Account模型

class Account < ApplicationRecord
  has_many :transactions, 
    foreign_key: 'account_id', 
    primary_key: 'account_id'
end

Transaction模型

class Transaction < ApplicationRecord
  belongs_to :account, 
    optional: true, 
    foreign_key: 'account_id',
    primary_key: 'account_id'
end

3. 验证外键约束

执行迁移后,可以通过数据库命令验证约束是否正确创建。例如在PostgreSQL中:

\d transactions

查看外键约束的引用目标,确认是accounts(account_id)而非accounts(id)。

内容的提问来源于stack exchange,提问作者Joshua Ondieki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 18:07:25