I'm stuck with this simple selection task. I have this models:
# id :integer(4) not null, primary key
# category :string(255)
# content :text
class Question < ActiveRecord::Base
has_many :choices, :dependent => :destroy
accepts_nested_attributes_for :choices
end
# id :integer(4) not null, primary key
# content :text
# correct :boolean(1)
# question_id :integer(4)
class Choice < ActiveRecord::Base
belongs_to :question
end
When I create a new question, I want to specify in a nested form not only the content
of the Question
, but even the content
of 3 Answer
objects, and select with a radio button which one is the correct
answer. In the new
action of the controller, I have this:
def new
@title = "New Question"
@question = Question.new
3.times { @question.choices.build }
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @question }
end
end
This is the form code:
<%= simple_form_for @question do |question_form| %>
<%= question_form.error_notification %>
<div class="inputs">
<%= question_form.input :content, :label => 'Question' %>
<%= question_form.input :category, :collection => get_categories, :include_blank => false %>
<% @question.choices.each do |choice| %>
<%= question_form.fields_for :choices, choice do |choice_fields| %>
<%= choice_fields.input :content, :label => 'Choice' %>
<%= choice_fields.radio_button :correct, true %>
<%= choice_fields.label :correct, 'Correct Answer' %>
<% end %>
<% end %>
</div>
<div class="actions">
<%= question_form.button :submit %>
</div>
<% end %>
The problem is that this code produce three radio buttons with different names: you can select more than one correct answer, and this is not the correct behaviour. The names of the three radio buttons are question[choices_attributes][0][correct]
, question[choices_attributes][1][correct]
and question[choices_attributes][2][correct]
.
The question is: how can I create three radio buttons with the same name, in order to select one and only one correct answer? How can I create a correct params
array, in order to save them in the create
action in this way:
def create
@question = Question.new(params[:question])
# render or redirect stuff....
end
Thank you very much!