views:

24

answers:

0

Hi,

I am trying to build a quiz of sorts. I would like my form to be able to build one question with 4 or more answers. 4 answers are inputted by default with the ability to add more answers dynamically with javascript. I have modeled it off the code in Ryan Bate's railscasts "Nested Model Forms".

My dilemma comes with setting the correct answer. My question model has_many answers, and so I have a correct_answer_id column in my Question model to refer to the correct answer. I would like to have a form field mapping to this attribute, whether that be a checkbox or radio button.

My code for the new action which sets up the form is:

def new
  @contest = Contest.new(:user_id => current_user.id)  
  q = @contest.build_question
  4.times { q.answers.build }
end

The problem is that the Answer objects have only been instantiated, and not yet saved, and thus don't have id's to map for the correct_answer_id attribute.

My form View Code:

-form_for @contest do |f|
……
  -f.fields_for :question do |builder|
    =render 'question_fields', :f => builder
  %br

-----
question_fields Partial : 

.fields
  =f.label :content, "Question"
  =f.text_field :content
  -f.fields_for :answers do |builder|
    =render 'answer_fields', :f => builder
    =f.radio_button :correct_answer_id,  … <---- this where I am unclear
    %br
  %p
    = link_to_add_fields "Add Answer", f, :answers  

Solutions I have considered include saving the answer objects in the new action so they have ID's, or setting up some kind of virtual attribute with extra logic that the radio button maps to. Any help would be greatly appreciated. Thanks!

-Tom