簡體   English   中英

ActiveRecord::InvalidForeignKey on has_many 通過關系

[英]ActiveRecord::InvalidForeignKey on has_many through relationship

嘗試通過 ProjectUser model 銷毀具有許多用戶的項目時遇到以下錯誤。

使用 pgsql、rails 6.0.3、ruby 2.7...

我不確定在這種情況下我缺少什么。 有人可以闡明一下嗎?

這是完整的錯誤:

ActiveRecord::InvalidForeignKey in ProjectsController#destroy

PG::ForeignKeyViolation: ERROR: update or delete on table "projects" violates foreign key constraint "fk_rails_1bf16ed5d0" on table "project_users" DETAIL: Key (id)=(8) is still referenced from table "project_users".

這是我的 model、控制器和架構:

項目控制器.rb

def destroy
  @project.destroy
  redirect_to projects_url, notice: 'Project was successfully destroyed.'
end

項目.rb

class Project < ApplicationRecord
  has_many :project_users
  has_many :users, through: :project_users
end

用戶.rb

class User < ApplicationRecord
  has_many :project_users
  has_many :projects, through: :project_users
end

項目用戶.rb

class ProjectUser < ApplicationRecord
  belongs_to :user
  belongs_to :project
end

架構.rb

create_table "project_users", force: :cascade do |t|
    t.bigint "user_id", null: false
    t.bigint "project_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["project_id"], name: "index_project_users_on_project_id"
    t.index ["user_id"], name: "index_project_users_on_user_id"
end

您必須首先銷毀與該項目關聯的每個項目用戶,然后再銷毀該項目。

或者您可以修改您的has_many關系並指定在銷毀項目時,每個相關記錄(不僅是 project_users,所有這些記錄)也會被銷毀:

has_many :project_users, dependent: :destroy

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM