Ruby on rails ActiveRecord::上的InvalidForeignKey具有多个通过关系
当我试图通过ProjectUser模型销毁一个有很多用户的项目时,我遇到了以下错误 使用pgsql、rails 6.0.3、ruby 2.7 我不确定我在这个案子里遗漏了什么。谁能帮我照一下吗 这是完全错误:Ruby on rails ActiveRecord::上的InvalidForeignKey具有多个通过关系,ruby-on-rails,ruby,postgresql,activerecord,rails-activerecord,Ruby On Rails,Ruby,Postgresql,Activerecord,Rails Activerecord,当我试图通过ProjectUser模型销毁一个有很多用户的项目时,我遇到了以下错误 使用pgsql、rails 6.0.3、ruby 2.7 我不确定我在这个案子里遗漏了什么。谁能帮我照一下吗 这是完全错误: ActiveRecord::InvalidForeignKey in ProjectsController#destroy PG::ForeignKeyViolation: ERROR: update or delete on table "projects" vio
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".
以下是我的模型、控制器和模式:
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\u 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
必须首先销毁与该项目关联的每个项目用户,然后销毁该项目 或者,您可以修改您的
has\u many
关系,并指定在销毁项目时,每个相关记录(不仅是项目用户,而且是所有用户)也将被销毁:
has_many :project_users, dependent: :destroy
谢谢你的快速回复!在
关联中添加dependent::destroy
会不会对用户或项目表数据造成任何伤害?它只会销毁相关的project\u用户
,如果project\u用户
也定义了dependent::destroy
关系,那么它将删除所有相关的记录。
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, dependent: :destroy