【发布时间】:2020-10-19 06:28:33
【问题描述】:
我在尝试通过 ProjectUser 模型销毁具有多个用户的项目时遇到以下错误。
使用 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".
这是我的模型、控制器和架构:
projects_controller.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
project_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
【问题讨论】:
标签: ruby-on-rails ruby postgresql activerecord rails-activerecord