ActiveRecord::InvalidForeignKey in ArticlesController#destroy
SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "articles" WHERE "articles"."id" = ?
我正在创建一个博客应用程序,每次尝试删除包含评论的文章时都会出现此错误。我怎样才能修好它?
告诉我要发布的代码,我会更新问题。
物品管理员:
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
模型中定义Article
,以便同时删除所有相关的Comment
,如下所示:
class Article < ApplicationRecord
has_many :comments, dependent: :delete_all
end
关于ruby-on-rails - Rails ActiveRecord::InvalidForeignKey在ArticlesController#destroy中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45522580/