2016-07-08 8 views
0

Wenn ich versuche zu zerstören ein Beitrag ich diesen Fehler:Wie man 'dependent:: destroy' an einen Beitrag mit Fragen und Antworten setzt? (PG :: ForeignKeyViolation)

PG::ForeignKeyViolation at /posts/92 
ERROR: update or delete on table "possible_answers" violates foreign key constraint "fk_rails_e2809cb61e" on table "answers" 
DETAIL: Key (id)=(1) is still referenced from table "answers". 

posts_controlller.rb

def destroy 
    @post = Post.find(params[:id]) 

    if @post.destroy 
     flash[:success] = "Post gelöscht." 
     redirect_to root_url 
    else 
     flash[:alert] = "Fehler." 
     redirect_to post_path(@post) 
    end 
    end 
  • A Post hat Fragen und Antworten
    • A Frage hat possible_answers und Antworten
    • A Antwort hat Antworten

post.rb

class Post < ActiveRecord::Base 
    has_many :questions, dependent: :destroy 
    has_many :replies, dependent: :destroy 
end 

question.rb

class Question < ActiveRecord::Base 
    belongs_to :post 

    has_many :possible_answers, dependent: :destroy 
    has_many :answers, dependent: :destroy 

    accepts_nested_attributes_for :possible_answers, reject_if: proc { 
    |attributes| attributes['title'].blank? 
    } 
end 

possible_answer.rb

class PossibleAnswer < ActiveRecord::Base 
    belongs_to :question 
end 

answer.rb

class Answer < ActiveRecord::Base 
    belongs_to :reply 
    belongs_to :question 
    belongs_to :possible_answer 
end 

reply.rb

Antwort

0

ich hinzugefügt haben "on_delete:: cascade "an die Fragen, Antworten, mögliche Antworten und Antworten Tabelle. Jetzt kann ich normalerweise einen solchen Beitrag löschen.

d.h .:

class CreatePossibleAnswers < ActiveRecord::Migration 
    def change 
    create_table :possible_answers do |t| 
     t.references :question, index: true, foreign_key: {on_delete: :cascade} 
     t.string :title 

     t.timestamps null: false 
    end 
    end 
end 
Verwandte Themen