简体   繁体   English

Rails中的外键-错误

[英]Foreign Key in Rails - Errors

I'm trying to add a new foreign key column to my Customers table. 我试图将新的外键列添加到我的客户表。 This is my migration: 这是我的迁移:

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

These are the errors I'm getting: 这些是我得到的错误:

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

What does any of that mean? 那是什么意思? I don't know what fk_rails_$NUMBER is. 我不知道fk_rails_ $ NUMBER是什么。

You're trying to add foreign keys twice by calling add_reference and add_foreign_key . 您正在尝试通过调用add_referenceadd_foreign_key两次添加外键。 The docs will tell you more, but basically add_foreign_key adds a key and add_reference can add a foreign key (which you are doing with foreign_key: true in your code above), so you should just use one or the other. 文档会告诉您更多信息,但基本上add_foreign_key添加了一个键,而add_reference 可以添加了一个外键(您正在使用foreign_key:在上面的代码中为true),因此您应该只使用其中一个。

If I were you I would just use add_foreign_key, it seems more suited to what you're trying to do: 如果我是您,我只会使用add_foreign_key,它似乎更适合您要执行的操作:

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

It means that you are trying to create a foreign key constraint that duplicates one you already have. 这意味着您正在尝试创建一个外键约束,该约束与您已经拥有的外键约束重复。

This line creates a foreign key constraint on customers referencing companies , as well as creates the company_id column 此行在引用companies customers上创建外键约束,并创建company_id

add_reference :customers, :company, foreign_key: true

This line is trying to do the foreign key constraint again 该行正在尝试再次执行外键约束

add_foreign_key :customers, :companies

Just remove one or the other, depending on whether or not you also need to add the company_id column 只需删除一个或另一个,这取决于您是否还需要添加company_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM