Rails中的嵌套表单:问题答案

时间:2015-02-16 19:44:35

标签: ruby-on-rails forms ruby-on-rails-4 model nested

我的rails应用程序有问题。

我的模特:
测验:姓名
问题:text,quiz_id
回答:text,question_id
right_answer:question_id,answer_id

测验有很多问题。单个问题有很多答案,答案只有一个正确答案。

我该如何解决这个问题?

这是我的表格:

    <%= form_for([@quiz, @question]) do |f| %>
      <% if @question.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(@question.errors.count, "error") %> prohibited this question from being saved:</h2>

          <ul>
          <% @question.errors.full_messages.each do |message| %>
            <li><%= message %></li>
          <% end %>
          </ul>
        </div>
      <% end %>


      <div class="field">
        <%= f.label :text %><br>
        <%= f.text_field :text %>
      </div>

        <%= f.fields_for :answers do |u| %>
            <%= u.text_field :text, class: "form-control", id: "answer"%>
        <% end %>

        <div class="actions">
    <%= f.submit %>

我想在每个答案中添加一个单选框,以选择哪个答案是正确的。

问题 - 控制器:

def new
  @question = Question.new
  @question.answers.build
end

  def create
    @question = Question.new(question_params)
    @question.quiz_id = @quiz.id
    i = 0
    until question_params[:answers_attributes].count
      @answer = @question.answers.new(question_params[:answers_attributes]["#{i}"])
      @answer.save
      i += 1
    end


    respond_to do |format|
      if @question.save
        format.html { redirect_to quiz_questions_path(@quiz), notice: 'Question was successfully created.' }
        format.json { render :show, status: :created, location: @question }
      else
        format.html { render :new }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
  end

我如何在我的控制器和我的表单中执行此操作,因为我只有一个right_answer但我的表单中需要4个单选按钮?

由于

2 个答案:

答案 0 :(得分:1)

在答案表中添加一个新的布尔字段correct_answer

rails g migration add_correct_answer_to_answer correct_answer:boolean

questions_controller.rb

def new
  @question = Question.new
  4.times { @question.answers.build } # you can do it dynamically
end

def question_params
  params.require(:question).permit(:text, answers_attributes: [:id, :text, :correct_answer])
end

问题/ _form.rb

<%= f.fields_for :answers do |builder| %>
  <%= render 'answer', f: builder %>
<% end %>

问题/ _answer.html.erb

<%= f.label :text, "Answer" %>
<%= f.text_field :text %>
<%= f.radio_button :correct_answer %>

然后,您可以创建问题模型中的范围,以便轻松获得特定问题的正确答案。

答案 1 :(得分:1)

= f.collection_radio_buttons:answer_id,@ question.answers.all,:id,:name_with_initial