我坚持这个简单的选择任务.我有这个机型:
# 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
当我创建一个新问题时,我想以嵌套形式指定问题的内容,甚至指定3个答案对象的内容,并选择一个单选按钮,哪一个是正确的答案.在控制器的新动作中,我有:
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 %>
问题是这个代码产生三个不同名称的单选按钮:你可以选择多个正确的答案,这不是正确的行为.三个单选按钮的名称是问题[choice_attributes] [0] [正确],问题[choice_attributes] [1] [正确]和问题[choice_attributes] [2] [正确].
问题是:如何创建三个具有相同名称的单选按钮,以便选择一个唯一的正确答案?如何创建一个正确的params数组,以便以这种方式将它们保存在创建操作中:
def create @question = Question.new(params[:question]) # render or redirect stuff.... end
非常感谢你!
解决方法
这是一个非答案,但我建议您尝试Formtastic.它使得处理这样的嵌套模型,如STUPID EASY:
https://github.com/justinfrench/formtastic