0

I'm trying to build out a survey with a rails app. My rails application has two models: Question has_many :answers and Answer belongs_to :question

I'm trying to iterated through all the questions and all their associated answers and make a checkbox option on all the answers for that associated question. How would I go about making checkboxes? Here's what I have so far. Would this need to be wrapped in a Form for each question too?

 <% @questions.each do |question| %>
  <tr>
    <td><%= question.content %></td><br>
    <% question.answers.each do |answer_choice| %>
         <%= form.check_box :answer_choice %>
    <% end %>
  </tr>
  <% end %>
0

1 Answer 1

1

If I understand correctly you want to create a nested form for each answer within the question form. You can do it like this:

In Question.rb set accepts_nested_attributes_for:

class Question< ActiveRecord::Base
  has_many :answers
  accepts_nested_attributes_for :answers

Then you can make a form something like this:

 <% @questions.each do |question| %>
    <%= form_for @question do |f|
       <%= f.fields_for :answers do |answer_builder| %>
           <%= answer_builder.check_box :answer_choice %>
       <%end%>
    <%= f.submit %>
    <%end%>
 <% end %>

Now the answer models will automatically be updated when you submit the question form. If you have a question_params method in your controller make sure to set it to allow parameters for answers as well, e.g.,:

def question_params
    params.require(:question).permit(:question_name, answers_attributes: [:answer_choice])
end

Ryan Bates has an excellent Railscast on nested forms. http://railscasts.com/episodes/196-nested-model-form-part-1

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

Comments

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.