1

I am creating a survey with the following data model:MathTest has_many math_questions

On MathTest#update I want to create one form for every question. The form should look something like this:

<%= form_for(mathtest) do %>
  <% math_question.each do |question| %>
    <%= f.label :answer %>
    <%= f.text_field :answer %>
    <%= f.hidden_field math_question.id %>
  <% end %>

  <% f.submit %>
<% end %>

I want to send the MathTest Controller a set of tuples with a math_question id and the answer for that question. Then in the Controller, I can call another method that evaluates each question's answer.

How do I write my form to send the appropriate tuple?

0

1 Answer 1

1

This should do it:

<%= form_for(mathtest) do |f| %>
  <% math_question.each do |question| %>
    <%= f.fields_for :answer do |ff| %>
      <%= ff.label :answer %>
      <%= ff.text_field :answer %>
    <% end %>
  <% end %>

  <% f.submit %>
<% end %>

Also edit the model:

class MathTest < ActiveRecord::Base
  has_many :math_questions
  accepts_nested_attributes_for :math_questions

fields_for documentation: http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for

Sign up to request clarification or add additional context in comments.

3 Comments

You also need to put 'accepts_nested_attributes_for :math_questions' in your math test model
I would also consider adding the cocoon gem.
I'm getting an error here: undefined method model_name' for Fixnum:Class` Where it refers to the following line: <% f.fields_for question.answer do |ff| %>. Not sure why, but check this pastie for the slightly modified version of your answer I tried: pastie.org/private/padhgvgrllayh20nedpxq

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.