mercredi 22 février 2017

How can I use fields_for to update a has_many association

I am making a quiz, and I have a Survey Model, Question Model and a Choice model I am looping over all of the questions and showing the choices for that question there is also a column on the choices table for the answer they had given, which is what I am trying to update.

Here is my code.

SurveyController

def show
  @survey = Survey.find(params[:id])
end

Survey Model

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

Question Model

class Question < ActiveRecord::Base
  attr_accessible :question
  has_many :choices
  belongs_to :survey
end

Choice Model

class Choice < ActiveRecord::Base
  attr_accessible :name
  belongs_to :question
end

Survey Show View

<div class="modal-wrap">
  <div class="modal-header">
    <% @survey.questions.size.times do %>
      <span></span>
    <% end %>
  </div>
  <div class="modal-bodies">
    <%= form_for @survey do |form| %>
      <% @survey.questions.each.with_index(1) do |question, index| %>
        <div class="modal-body">
          <div class="title">Question <%= index %></div>
            <div class="description"><%= question.question %></div>
              <%= fields_for :choices, question.choices do |choice_fields| %>
                <%= choice_fields.text_field :name %>
              <% end %>
              <div class="text-center">
                <div class="button">Next</div>
              </div>
            </div>
          <% end %>
        <% end %>
    </div>

I can't get the form_for to work properly, can someone help me get this to work please?

Aucun commentaire:

Enregistrer un commentaire