【发布时间】:2011-07-02 17:26:30
【问题描述】:
我被这个简单的选择任务困住了。我有这个模型:
# 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
当我创建一个新问题时,我想以嵌套形式指定 Question 中的 content,甚至是 3 个 Answer 对象中的 content,然后使用单选按钮进行选择一个是correct 答案。在控制器的new 动作中,我有这个:
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
这是表单代码:
<%= 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 %>
问题在于这段代码生成了三个名称不同的单选按钮:您可以选择多个正确答案,这不是正确的行为。三个单选按钮的名称是question[choices_attributes][0][correct]、question[choices_attributes][1][correct] 和question[choices_attributes][2][correct]。
问题是:如何创建三个具有相同名称的单选按钮,以便选择一个且只有一个正确答案?如何创建正确的params 数组,以便以这种方式将它们保存在create 操作中:
def create
@question = Question.new(params[:question])
# render or redirect stuff....
end
非常感谢!
【问题讨论】:
-
我也有同样的问题,为什么没人帮忙回答? :(
-
你找到答案了吗?把我的头发扯下来!
标签: ruby-on-rails-3 radio-button nested-forms nested-attributes