【发布时间】:2018-01-11 14:11:36
【问题描述】:
PG::ForeignKeyViolation:错误:更新或删除表“用户” 违反表上的外键约束“fk_rails_fd01e11a00” "user_tasks" DETAIL: Key (id)=(4) 仍然从表中引用 “用户任务”。 : DELETE FROM "users" WHERE "users"."id" = $1
一个用户可以将任务分配给另一个用户。在那里,我创建了一个连接任务表并自行连接用户表的直通表。表格如下所示:
|用户 ID |任务ID | to_user_id |
UserTask(迁移):
class CreateUserTasks < ActiveRecord::Migration[5.0]
def change
create_table :user_tasks do |t|
t.references :user, index: true, foreign_key: true
t.references :task, foreign_key: true, unique: true
t.references :to_user, index: true
t.timestamps
end
add_foreign_key :user_tasks, :users, column: :to_user_id
add_index :user_tasks, [:user_id, :to_user_id], unique: false
end
end
型号如下:
用户:
class User < ApplicationRecord
has_many :user_tasks
has_many :tasks, through: :user_tasks, dependent: :destroy
end
用户任务:
class UserTask < ApplicationRecord
belongs_to :user
belongs_to :task
belongs_to :to_user, class_name: "User"
end
任务:
class Task < ApplicationRecord
has_many :user_tasks
has_many :users, through: :user_tasks, dependent: :destroy
has_many :to_users, through: :user_tasks, dependent: :destroy
end
问题是当我尝试删除用户时,它会产生错误外键约束错误,该键仍然是来自用户表的引用 请帮助指导我在这里做错了什么。
【问题讨论】:
-
UserTask 是连接表吧?
标签: mysql ruby-on-rails postgresql activerecord