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

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

私はブログアプリケーションを作成していますが、コメントを含む記事を削除しようとするたびにこのエラーが発生します。どうすれば修正できますか?Rails ActiveRecord :: ArticlesController内のInvalidForeignKey

投稿するコードを教えてください。質問を更新します。

記事コントローラ:

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

今、私はあなたがすべての関連Commentもこのように、削除されるので、dependent: :delete_allArticleでモデルを定義することができ、この問題を回避するには、新しいエラー

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

を持っている:dependent: :delete_allを使用して

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

ありがとうございますが、私は新しいエラーがあります – bockdavidson

+0

@bockdavidson申し訳ありませんが、私は誤植がありました。更新された回答を確認してください(依存する必要はありません)。 – Gerry

+0

それは働いた!どうもありがとうございます! – bockdavidson

4

はしていません検証を使用するので、適切に検証することなくレコードを直接削除します。レコードを安全に検証する場合は、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/ –

関連する問題