多态|自我参考| Rails活动记录模型

时间:2017-08-03 19:41:42

标签: mysql ruby-on-rails postgresql activerecord

  

PG :: ForeignKeyViolation:错误:更新或删除表"用户"   违反外键约束" fk_rails_fd01e11a00"桌子上   " user_tasks" DETAIL:Key(id)=(4)仍然从表中引用   " user_tasks&#34 ;. :DELETE FROM"用户"用户"。" id" = $ 1

用户可以将任务分配给其他用户。因为我创建了一个连接任务表的自动表,并自己加入了用户表。表格如下:

| user_id | task_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

UserTask

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

问题是当我尝试删除用户时会产生错误外键约束错误,该键仍然是来自用户表的引用 请帮助指导我在这里做错了什么。

3 个答案:

答案 0 :(得分:0)

class User < ApplicationRecord
 has_many :user_tasks, dependent: :destroy
 has_many :tasks, through: :user_tasks
end

我希望它有效吗?

交叉手指&lt; 3

答案 1 :(得分:0)

i think your issue is in the join model, UserTask. I think it should be declared like this, without the commented out line below.:

UserTask:

class UserTask < ApplicationRecord
  belongs_to :user
  belongs_to :task
  **#belongs_to :to_user, class_name: "User"**
end

Then you should be able to delete a user and the record in the join model,user_task, as you have specified the dependent option correctly. Check a detailed explanation here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html, section Delete or destroy?

答案 2 :(得分:0)

这是解决方案更少答案:

据我所知,在google.com上搜索后,我发现在使用dependent: :destroy关联时,会查找对象id进行删除。

但在我的情况下,我使用三个参考如下

taskuserto_user因此dependent: :destroy将删除这些关联,而每个对象id将在{0}中删除task_id },user_idto_user_id。它只能删除taskuser但不会删除to_user_id,因为它只知道user_id而不是to_user_id