gpt4 book ai didi

ruby-on-rails - 我在 Ruby on Rails SQLite3::ConstraintException: FOREIGN KEY constraint failed 中有这个问题

转载 作者:行者123 更新时间:2023-12-05 00:54:04 24 4
gpt4 key购买 nike

我是 Ruby on Rails 的新手。我尝试制作标签并可以选择删除标签。当我想销毁标签时,我收到此错误 SQLite3::ConstraintException: FOREIGN KEY constraint failed.

ActiveRecord::InvalidForeignKey in TagsController#destroy

这是我在 Controller 中删除标签的代码:

def destroy
@tag = Tag.find(params[:id])
@tag.destroy

flash.notice = "Tag '#{@tag.name}' Deleted!"

redirect_to tags_path
end

这是 schema.rb

ActiveRecord::Schema.define(version: 2021_03_20_115719) do

create_table "articles", force: :cascade do |t|
t.string "title"
t.text "body"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end

create_table "comments", force: :cascade do |t|
t.string "author_name"
t.text "body"
t.integer "article_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["article_id"], name: "index_comments_on_article_id"
end

create_table "taggings", force: :cascade do |t|
t.integer "tag_id", null: false
t.integer "article_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["article_id"], name: "index_taggings_on_article_id"
t.index ["tag_id"], name: "index_taggings_on_tag_id"
end

create_table "tags", force: :cascade do |t|
t.string "name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end

add_foreign_key "comments", "articles"
add_foreign_key "taggings", "articles"
add_foreign_key "taggings", "tags"
end

最佳答案

FOREIGN KEY 约束失败通常意味着您的数据库中有另一条记录仍然有一个 belongs_to 关联设置到该记录,因此您无法删除它。

在您的示例中,有一个 article 带有您要删除的标签。

create_table "taggings", force: :cascade do |t|
t.integer "tag_id", null: false # << here the association
t.integer "article_id", null: false

# in combination with

add_foreign_key "taggings", "articles"
add_foreign_key "taggings", "tags" # << here the foreign key constraint

您的 schema.rb 表明您有一个 taggings 连接表,该表将文章与标签和在此表中的两个属性(tag_idarticle_id) 不能为 nil,并且必须包含标识关联表上记录的有效 id。

这意味着当您想要删除特定标签时,您必须首先从 taggings 连接表中删除该标签。以下代码应该可以工作:

def destroy
@tag = Tag.find(params[:id])
@tag.articles.clear # << add this line
@tag.destroy

flash.notice = "Tag '#{@tag.name}' Deleted!"

redirect_to tags_path
end

阅读 collection.clear以及 has_and_belongs_to 关联在 Rails Guides 中的一般用法.

关于ruby-on-rails - 我在 Ruby on Rails SQLite3::ConstraintException: FOREIGN KEY constraint failed 中有这个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66724728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com