1

How can I achieve something like this?
The structure is => a test has many questions, and a question has many answers.

I have questions = @test.questions.build and questions.answers.build in the controller.

form_for @test do |f|
  f.fields_for :questions do |question_f|
    question_f.fields_for :answers do |answer_f|
      # answer form here

It works untill the fields_for :answers.

What am I missing? Thanks!

1 Answer 1

3

You should also put accepts_nested_attributes_for in your Test and Question model if you want use nested form:

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

class Question < ActiveRecord::Base
  attr_accessible :answers_attributes
  has_many :answers, dependent: :destroy
  accepts_nested_attributes_for :answers
end

Try this:

form_for ([@test, @question]) do |f|

and in your new action in controller:

@test = Test.new
@question = Question.new
@test.questions.build
@question.answers.build 
Sign up to request clarification or add additional context in comments.

2 Comments

It already had the accepts_nested_attributes_for in both Test and Question. The nested form for question works fines, the problem is with the answer inside question.
loop around the @questions and build answers for each question.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.