Ruby on Rails: How to get nested_form_for new child ID

158 views Asked by At

I have QuestionSet, Question, and Choice tables

class QuestionSet < ActiveRecord::Base
    attr_accessible :name
    has_many :questions
end

class Question < ActiveRecord::Base
    attr_accessible :name, :correct_answer

    belongs_to :question_set
    has_many :choices
end

class Choice < ActiveRecord::Base
    attr_accessible :question_id, :value
    belongs_to :question
end

I want to assign the id of Choice as the correct_answer for Question. But since new nested_form_for child objects don't have real IDs yet, I can only assign the correct_answer for choices that have been saved already, but doesn't work for choices that have just been created through link_to_add. The simplified 'view' code below:

<!-- BTW 'f' below is QuestionSet -->
<%= f.fields_for :questions do |f_f| %>
    <!-- Question Name -->
    <%= f_f.text_field :name %>

    <%= f_f.fields_for :choices do |f_f_f| %>
        <!-- Designate as Correct Answer -->
        <%= f_f.radio_button :correct_answer, f_f_f.object.id %><!-- THIS IS THE PROBLEM-->
        <!-- Choice Name -->
        <%= f_f_f.text_field :value %> 

        <%= f_f_f.link_to_remove "Remove Choice" %>
    <% end %>
    <%= f_f.link_to_add "Add Choice", :choices %>

    <%= f_f.link_to_remove "Remove Question" %>
<% end %>

<%= f.link_to_add "Add Question", :questions %>

Again the code only works and assigns the id of the choice-child as the 'correct_answer' of the Question only if the choice was saved before already and therefore it has an id already. But, it doesn't work for those newly created choice-children created by the link_to_add.

Any help would be gladly appreciated. Thanks! :)

1

There are 1 answers

6
DeeY On

why not move :correct_answer field to the Choices and make it boolean? This will simplify things a lot