简体   繁体   English

在Rails中添加外键

[英]Add foreign key in Rails

I have two tables, casino_users and accounts . 我有两个表, casino_usersaccounts

I want to make casino_users.username a foreign key that references accounts.email . 我想打casino_users.username一个外键引用accounts.email

I tried this: 我尝试了这个:

class AddForeignKeyToCASinoUsers < ActiveRecord::Migration[5.2]
  def up
    add_foreign_key :casino_users, :accounts, column: :username, primary_key: "email"
  end 

  def down
    remove_foreign_key :casino_users, column: :username
  end 
end

but it gives me an error Cannot add or update a child row: a foreign key constraint fails . 但它给我一个错误Cannot add or update a child row: a foreign key constraint fails

Is there something wrong with the syntax I am using? 我使用的语法有问题吗?

First guess is that you have data in the existing tables which is incompatible with the constraint you are now adding. 首先猜测是您现有表中的数据与您现在添加的约束不兼容。 If that doesn't seem to be the issue would be good to give a little more context on when this error occurred. 如果那似乎不是问题,那么最好提供更多有关此错误发生时间的上下文。 When you tried to run the migration is what I am assuming. 当您尝试运行迁移时,这就是我的假设。

PS You may get into trouble by attempting to use a set a primary key which is syntatically meaningful and also subject to change. PS:尝试使用一个主键在语法上有意义并且也可能会发生变化,因此您可能会遇到麻烦。 If you leave the primary key set to id, and linke users to accounts by id, you will have an easier time of it when, for example some day you ant to allow users to change their email address. 如果您将主键设置为id,并通过id将用户链接到帐户,那么您将有一个更轻松的时间,例如,某天您希望允许用户更改其电子邮件地址。 If you want to make sure there is one account associated with an email address that is easy enough to achieve with a uniq constraint on the email field. 如果要确保有一个与电子邮件地址关联的帐户,该帐户很容易实现,并且在电子邮件字段上具有唯一约束。

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

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