gpt4 book ai didi

ruby-on-rails - Rails 中的外键 - 错误

转载 作者:行者123 更新时间:2023-11-29 12:54:56 26 4
gpt4 key购买 nike

我正在尝试向我的 Customers 表中添加一个新的外键列。这是我的迁移:

class AddCompanyForeignKeyToCustomers < ActiveRecord::Migration[5.1]
def change
add_reference :customers, :company, foreign_key: true
add_foreign_key :customers, :companies
end
end

这些是我遇到的错误:

rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::DuplicateObject: ERROR: constraint "fk_rails_ef51a916ef" for relation "customers" already exists
: ALTER TABLE "customers" ADD CONSTRAINT "fk_rails_ef51a916ef"
FOREIGN KEY ("company_id")
REFERENCES "companies" ("id")

ActiveRecord::StatementInvalid: PG::DuplicateObject: ERROR: constraint "fk_rails_ef51a916ef" for relation "customers" already exists
: ALTER TABLE "customers" ADD CONSTRAINT "fk_rails_ef51a916ef"
FOREIGN KEY ("company_id")
REFERENCES "companies" ("id")

PG::DuplicateObject: ERROR: constraint "fk_rails_ef51a916ef" for relation "customers" already exists

这是什么意思?我不知道 fk_rails_$NUMBER 是什么。

最佳答案

这意味着您正在尝试创建一个复制您已有的外键约束。

此行在引用 companiescustomers 上创建外键约束,并创建 company_id

add_reference :customers, :company, foreign_key: true

这一行又在尝试做外键约束

add_foreign_key :customers, :companies

只需删除一个或另一个,具体取决于您是否还需要添加 company_id

关于ruby-on-rails - Rails 中的外键 - 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45699327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com