I'm building a quiz and using nested forms to submit answers. I guess i'm looking on how to submit an array of nested forms?
I have the following setup:
Quiz
has_many :quiz_answers, dependent: :destroy
accepts_nested_attributes_for :quiz_answers, allow_destroy: true
Quiz Answer
belongs_to :quiz, optional: true
These next two create the Quiz question and options (ie. a, b, c, d) which are setup by an admin. This allows questions to be added and taken out as needed on the fly. This part works as it should and I have no issues here.
Quiz Question
has_many :quiz_options, dependent: :destroy
accepts_nested_attributes_for :quiz_options, allow_destroy: true
Quiz Option
belongs_to :quiz_question, optional: true
This issue I'm having is when a user begins a quiz, how can I iterate through each question and have a user submit an option, click next and go on to the next question until all are completed? So far I have it working in the sense it's saving one answer to the database, but it lists all questions:
class QuizzesController < ApplicationController
def new
@quiz = Quiz.new
@quiz_question = QuizQuestion.where(active: true)
@quiz.quiz_answers.build
end
def create
@quiz = Quiz.new(quiz_params)
respond_to do |format|
if @quiz.save
format.html { redirect_to quiz_url(@quiz), notice: "Quiz was successfully created." }
format.json { render :show, status: :created, location: @quiz }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @quiz.errors, status: :unprocessable_entity }
end
end
end
end
Form
<%= form_with(model: quiz) do |form| %>
<%= form.fields_for :quiz_answers do |builder| %>
<%= render 'quiz_answer', form: builder %>
<% end %>
<%= form.submit "Submit", class: 'btn btn-primary' %>
<% end %>
Partial
<% @quiz.each do |question| %>
<h2><%= question.question %></h2>
<% question.quiz_options.each do |o| %>
<%= form.radio_button :answer, o.answer %> <%= o.answer %>
<% end %>
<% end %>
So in summary, I'm wondering if it's possible to have question 1, user submits answer, Question 2, user submits answers, etc. in a nested form environment all from an array of predetermined questions and answers?