I have a survey app that allows people to create questions. When a user creates a new question they can also supply answer options. For Ex. Question: What color is the sky? Answer Options: Blue, Red, Purple.
Right now, my single form allows for the creation of the questions model, and options model, but I want to create multiple options from the same form.
Should I create a unbounded form_tag that allows a user to submit an array of hashes, and iterate over that array to create each option model record? Or is there another way of doing this?
option.rb
class Option < ActiveRecord::Base
belongs_to :question
end
question.rb
class Question < ActiveRecord::Base
has_many :options
accepts_nested_attributes_for :options
end
Questions Controller
class QuestionsController < ApplicationController
def new
@question = Question.new
@question.options.build
end
def create
@question = Question.new(question_params)
if @question.save
redirect_to @question
else
render 'new'
end
end
private
def question_params
params.require(:question).permit(:title, :desc, options_attributes:[:id, :scope, :option, :question_id])
end
end
_form.html.erb
<%= form_for @question do |f| %>
<%= f.text_field :question, class: "form-control", placeholder: "Survey Question?" %>
<%= f.fields_for :options do |u| %>
<%= u.text_field :option, class: "form-control", placeholder: "Answer Option 1", id: "answer"%>
<%= u.text_field :option, class: "form-control", placeholder: "Answer Option 2", id: "answer"%>
<%= u.text_field :option, class: "form-control", placeholder: "Answer Option 3", id: "answer"%>
<% end %>
<%= f.submit 'Submit', class: "btn btn-default" %>