在表上插入或更新违反外键约束(错误)

时间:2018-04-11 13:24:33

标签: ruby-on-rails postgresql

我使用User拥有AuthorizedReceiverPersonalInfo的多态关联。

class User < ApplicationRecord
  has_many :authorized_receivers
  has_one :personal_info, as: :info_owner
end

class AuthorizedReceiver < ApplicationRecord
  belongs_to :user
  has_one :personal_info, as: :info_owner
end

class PersonalInfo < ApplicationRecord
  belongs_to :info_owner, polymorphic: true
end

当我向用户创建第一个AuthorizedReceiver并尝试更新此PersonalInfo的{​​{1}}时,我获得了成功。但是,当我创建第二个AuthorizedReceiver并尝试更新其AuthorizedReceiver时,我出现以下错误:

PersonalInfo

我做错了什么?

PS:如果我对ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: insert or update on table "personal_infos" violates foreign key constraint "fk_rails_796da13f22" DETAIL: Key (info_owner_id)=(2) is not present in table "users". : INSERT INTO "personal_infos" ("info_owner_id", "full_name", "created_at", "updated_at", "info_owner_type") VALUES ($1, $2, $3, $4, $5) RETURNING "id" 做同样的事情(即,尝试更新第二个用户的User成功),也不会发生同样的情况。

编辑:

PersonalInfo

这导致了一个错误的fk约束仍然指向用户:

class CreatePersonalInfos < ActiveRecord::Migration[5.1]
  def up
    create_table :personal_infos do |t|
      t.references :user, foreign_key: true, index: true, unique: true
  end
end


class AddInfoOwnerToPersonalInfos < ActiveRecord::Migration[5.1]
  def up
    rename_column :personal_infos, :user_id, :info_owner_id
    add_column :personal_infos, :info_owner_type, :string

    add_index :personal_infos, [ :info_owner_type, :info_owner_id]

    PersonalInfo.update_all(info_owner_type: 'User')

    change_column :personal_infos, :info_owner_type, :string, null: false
  end

  def down
    rename_column :personal_infos, :info_owner_id, :user_id
    remove_column :personal_infos, :info_owner_type
  end
end

1 个答案:

答案 0 :(得分:1)

像我和@PavelMikhailyuk一样评论道:

您刚刚将该列重命名为info_owner_id

rename_column :personal_infos, :user_id, :info_owner_id

您还需要删除外键:

由于您更改了列名,因此Rails可能无法自动找到关联,那么您可能会尝试使用以下迁移删除foreign_key:

remove_foreign_key :personal_infos, column: :info_owner_id