首页 > 解决方案 > 当关联模型具有自定义表名时,Rails 5 的 belongs_to 问题。ActiveRecord::InvalidForeignKey 异常:PG::ForeignKeyViolation:

问题描述

Rails 5,当关联模型有自定义表名时,belongs_to 关系有问题。

下面是示例

class Department < ApplicationRecord
  self.table_name = 'custom_departments'
end
class Request < ApplicationRecord
  belongs_to :department, class_name: 'Department', foreign_key: 'department_id', optional: true
end

当我尝试保存请求对象时,它失败并出现以下错误

request = Request.new(department_id: 1)
request.save

**ActiveRecord::InvalidForeignKey Exception:PG::ForeignKeyViolation:ERROR:insert or update on table "requests" violates foreign key constraint "fk_rails_8aaaf05eb8"
Key (department_id)=(1) is not present in table "departments".**

谢谢

标签: ruby-on-railspostgresql

解决方案


仔细查看您从 PostgreSQL(不是 Rails)收到的错误消息:

insert or update on table "requests" violates foreign key constraint
...
is not present in table "departments".*

您在PostgreSQL 数据库中引用departments(not ) 的外键约束存在问题。custom_departments您最初创建了一个departments表并具有以下内容:

t.references :department, foreign_key: true

在一次迁移中。后来你改变主意并切换到custom_departments表,但忽略了修复数据库中的外键。

您需要删除旧的 FK(可能还有departments表)并添加在迁移中引用正确表的新 FK:

def change
  remove_foreign_key :requests, :departments
  drop_table :departments # Assuming this is what you really want of course
  add_foreign_key :requests, :custom_departments, column: :department_id
end

推荐阅读