ActiveRecord::InvalidForeignKey 在 has_many 通过关系

ActiveRecord::InvalidForeignKey on has_many through relationship

我在尝试通过 ProjectUser 模型销毁具有许多用户的项目时 运行 遇到以下错误。

使用 pgsql,rails6.0.3,ruby2.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".

这是我的模型、控制器和模式:

projects_controller.rb

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

project.rb

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

user.rb

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

项目_user.rb

class ProjectUser < ApplicationRecord
  belongs_to :user
  belongs_to :project
end

schema.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