samedi 31 octobre 2015

How to use checkboxes with nested form helpers - multiple answer input in survey app

I'm working my way through a (what I thought was) basic survey app and I've run into a little pickle.

Basically I want to allow my Poll app to be able to accept multiple answers via checkboxes. I've gotten to the point where I can input answers but it's passing an incrementing checkbox id (first one is 0, second is 1 etc) and it's not creating multiple records when multiple boxes are checked. Any help would be greatly appreciated.

form.html.erb

<label>
  <%= c.object.question.title %>
</label>
<div class="radio">
  <% c.object.question.possible_answers.each do |possible_answer| %>
    <p>
      <label>
        <%= possible_answer.title %>
        <%= c.check_box :possible_answer_id %>
        <%= c.hidden_field :question_id %>
      </label>
    </p>
  <% end %>
</div>

replies_controller.rb

class RepliesController < ApplicationController

  before_action :set_exam

  def new
    @reply = @exam.replies.build
    @exam.questions.each do |question|
      @reply.answers.build question: question
    end
  end

  def create
    @reply = @exam.replies.build(reply_params)
    if @reply.save
      redirect_to @exam, notice: "Thank you for completing the exam"
    else
      render :new
    end
  end

  private

  def set_exam
    @exam = Exam.find params[:exam_id]
  end

  def reply_params
    params.require(:reply).permit(:exam_id, { answers_attributes: [:value,      :question_id, :reply_id, :possible_answer_id] })
  end

end




Aucun commentaire:

Enregistrer un commentaire