2017-08-05 35 views
1
ActiveRecord::InvalidForeignKey in ArticlesController#destroy 

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

我创建一个博客的应用程序,每次我试图删除它有评论文章时出现此错误。我该如何解决它?的Rails的ActiveRecord :: InvalidForeignKey在ArticlesController#破坏

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

文章控制器:

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 

UPDATE

现在我有一个新的错误

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 

回答

4

为了避免这个问题,你可以在Article模型中定义dependent: :delete_all所以每一个相关Comment也被删除,就像这样:

class Article < ApplicationRecord 
    has_many :comments, dependent: :delete_all 
end 
+0

谢谢,但我有一个新的错误 – bockdavidson

+0

@bockdavidson对不起,我有一个错字;请检查更新的答案(它应该是“依赖”,而不是“依赖”)。 – Gerry

+0

它工作!非常感谢! – bockdavidson

4

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

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

验证是什么意思?记录将被删除,所以乳清你需要验证吗? –

+0

我发现这个http://notes.jerzygangi.com/dependent-destroy-vs-dependent-delete-all-in-rails-models/ –