ruby-on-rails - 当关联模型具有自定义表名时,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".**
谢谢
解决方案
仔细查看您从 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
推荐阅读
- dart - 未使用函数“_neverSatisfied”。飞镖(未使用的元素)
- ios - 为 iOS 项目开发 Pod - 改进工作方法
- javascript - 如何使用 Openlayers 设置新点的坐标?
- android - 未检测到 Android 构建工具
- r - 使用 venn.diagram 包的面积比例维恩图
- sql - 使用 sequelize node.js 执行查询时分组格式错误
- python - 使用函数一次附加多个列表
- sas - 我可以在 PROC CONTENTS 的数据集名称中使用通配符吗?
- python - Django登录方法不会将用户置于会话中
- python - 在点数组内搜索正方形