gpt4 book ai didi

ruby-on-rails - ArticlesController 中的 Rails ActiveRecord::InvalidForeignKey#destroy

转载 作者:数据小太阳 更新时间:2023-10-29 08:14:52 27 4
gpt4 key购买 nike

ActiveRecord::InvalidForeignKey in ArticlesController#destroy

SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "articles" WHERE "articles"."id" = ?

我正在创建一个博客应用程序,每次尝试删除其中包含评论的文章时都会出现此错误。我该如何解决?

让我知道要发布什么代码,我会更新问题。

文章 Controller :

class ArticlesController < ApplicationController
def new
@article = Article.new
end

def index
#@articles = Article.all
@articles = Article.paginate(:page => params[:page], :per_page => 10)
end

def show
@article = Article.find(params[:id])
end

def create
@article = Article.new(article_params)

@article.save
redirect_to @article
end

def edit
@article = Article.find(params[:id])
end

def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end

end

def destroy
@article = Article.find(params[:id])
@article.destroy

redirect_to articles_path
end
end

private
def article_params
params.require(:article).permit(:title, :text, :datee)
end

文章模型:

class Article < ApplicationRecord
has_many :comments
has_many :photos
end

评论模型:

class Comment < ApplicationRecord
belongs_to :article
end

更新

现在我有一个新的错误

ArgumentError in ArticlesController#destroy

Unknown key: :dependant. Valid keys are: :class_name, :anonymous_class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type, :index_errors

最佳答案

使用 dependent: :delete_all 不使用验证,因此它直接删除记录而没有正确验证。如果您希望安全地验证您的记录,请使用 dependent::destroy

class Article < ApplicationRecord
has_many :comments, dependent: :destroy
end

关于ruby-on-rails - ArticlesController 中的 Rails ActiveRecord::InvalidForeignKey#destroy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45522580/

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