0

I have models - Test, Question, and TeacherAnswers.

test.rb

class Test < ActiveRecord::Base
  has_many :questions, dependent: :destroy
  accepts_nested_attributes_for :questions
end

question.rb

class Question < ActiveRecord::Base
  belongs_to :test
  has_many :teacher_answers, dependent: :destroy
  accepts_nested_attributes_for :teacher_answers
end

teacher_answer.rb

class TeacherAnswer < ActiveRecord::Base
  belongs_to :question
end

and controllers test_controller.rb

---    
standard scaffold code
---
def test_params
      params.require(:test).permit(:title, 
                                    questions_attributes: [:question_text, :test_id, teacher_answers_attributes: [:teacher_answer_text, :correct, :question_id]],)
    end

question_controller.rb

---    
standard scaffold code
---
def question_params
      params.require(:question).permit(:question_text, :test_id,
                                        teacher_answers_attributes: [:teacher_answer_text, :correct, :question_id])
    end

When creating new test with questions and answers it creates everything correctly, but when updating:

  1. can't remove questions
  2. when saving it doesn't update the questions and answers, but saves new ones with already old ones i.e. when updating test with 2 questions, after saving it will have 4 questions.

2 Answers 2

1

You should permit :id and :_destroy in the test_params like below for the update and delete to work correctly.

def test_params
  params.require(:test).permit(:title, questions_attributes: [:id, :question_text, :test_id, :_destroy, teacher_answers_attributes: [:id, :teacher_answer_text, :correct, :question_id, :_destroy]])
end

Update

You should also add allow_destroy: true for test.rb and question.rb

class Test < ActiveRecord::Base
  has_many :questions, dependent: :destroy
  accepts_nested_attributes_for :questions, allow_destroy: true
end

class Question < ActiveRecord::Base
  belongs_to :test
  has_many :teacher_answers, dependent: :destroy
  accepts_nested_attributes_for :teacher_answers, allow_destroy: true
end
4
  • thank you. the :id solved update error. how to solve deleting problem?
    – MartinsB
    Aug 22, 2015 at 12:32
  • 1
    had to add also allow_destroy: true to test.rb and question.rb
    – MartinsB
    Aug 22, 2015 at 12:45
  • @MartinsB Yes. Good catch :)
    – Pavan
    Aug 22, 2015 at 12:51
  • @MartinsB Please accept the answer if it solves your problem :)
    – Pavan
    Aug 22, 2015 at 13:12
0
  1. accepts_nested_attributes_for by default does not allow deletion, use delete: true
  2. Pass id to form, via hidden tag

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.