Ruby on rails 当关联模型具有自定义表名时,Rails 5所属对象出现问题。ActiveRecord::InvalidForeignKey异常:PG::ForeignKeyViolation:
当关联模型具有自定义表名时,Rails 5在归属关系方面遇到问题 下面是一个例子Ruby on rails 当关联模型具有自定义表名时,Rails 5所属对象出现问题。ActiveRecord::InvalidForeignKey异常:PG::ForeignKeyViolation:,ruby-on-rails,postgresql,Ruby On Rails,Postgresql,当关联模型具有自定义表名时,Rails 5在归属关系方面遇到问题 下面是一个例子 class Department < ApplicationRecord self.table_name = 'custom_departments' end 谢谢您正在为不存在的部门创建请求。您需要引用现有对象 some_department = Department.all.first // get department you want to refer to request = Reques
class Department < ApplicationRecord
self.table_name = 'custom_departments'
end
谢谢您正在为不存在的部门创建请求。您需要引用现有对象
some_department = Department.all.first // get department you want to refer to
request = Request.new
request.department = some_department
request.save
您正在为不存在的部门创建请求。您需要引用现有对象
some_department = Department.all.first // get department you want to refer to
request = Request.new
request.department = some_department
request.save
仔细查看从PostgreSQL(而非Rails)获得的错误消息: 您的PostgreSQL数据库中引用
部门
(而不是自定义部门
)的外键约束有问题。您最初创建了一个departments
表,其内容如下:
t.references :department, foreign_key: true
在一次迁移中。后来,您改变了主意,切换到custom\u departments
表,但忽略了修复数据库中的外键
您需要删除旧FK(可能还有部门
表),并添加在迁移中引用正确表的新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
仔细查看从PostgreSQL(而非Rails)获得的错误消息: 您的PostgreSQL数据库中引用
部门
(而不是自定义部门
)的外键约束有问题。您最初创建了一个departments
表,其内容如下:
t.references :department, foreign_key: true
在一次迁移中。后来,您改变了主意,切换到custom\u departments
表,但忽略了修复数据库中的外键
您需要删除旧FK(可能还有部门
表),并添加在迁移中引用正确表的新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
在“自定义部门”表中是否已有ID=1的部门?是的,我在“自定义部门”表中有ID为1的行。在“自定义部门”表中是否已有ID=1的部门?是的,我在“自定义部门”表中有ID为1的行。