如何验证测验问题表格Rails

时间:2011-03-10 20:45:41

标签: ruby-on-rails

我有一个非常基本的表格,可以显示测验问题以及选择:

<%= form_tag(quiz_attempts_path, :method =>'post') %>
    <% @course_step.step.step_quiz.step_quiz_questions.each do |quiz_question| %>
        <h3><%= quiz_question.value %></h3>

        <% quiz_question.step_quiz_question_choices.each do |quiz_question_choice| %>
        <%= radio_button_tag("quiz_questions[#{quiz_question.id}]", quiz_question_choice.value, false)%>
        <%= quiz_question_choice.value%><br />
        <% end %>

    <% end %>
    <%= hidden_field_tag('step_quiz_id', @course_step.step.step_quiz.id)%>
    <%= hidden_field_tag('started', Time.now.utc)%>
    <%= submit_tag("Submit Quiz")%>
</form>

当我保存表单的结果时,我只保存摘要数据:(我是否需要使用某种模型验证进入此方法的数据?)

def create
    correct = 0
    incorrect = 0
    params[:quiz_questions].each do |step_quiz_question_id, chosen_answer|
      if StepQuizQuestion.find(step_quiz_question_id).correct?(chosen_answer)
        correct += 1
      else
        incorrect += 1
      end
    end

    QuizAttempt.create(:patient_id => current_user.id, :correct => correct, :incorrect => incorrect, :started => params[:started], :ended => Time.now, :step_quiz_id => params[:step_quiz_id])
  end

以下是我要保存的测验尝试模型。

class QuizAttempt < ActiveRecord::Base
  belongs_to :step_quiz
  belongs_to :patient

  attr_accessible :step_quiz_id, :patient_id, :started, :ended, :correct, :incorrect  
end


# == Schema Information
#
# Table name: quiz_attempts
#
#  id           :integer         not null, primary key
#  step_quiz_id :integer
#  patient_id   :integer
#  started      :datetime
#  ended        :datetime
#  correct      :integer
#  incorrect    :integer
#  created_at   :datetime
#  updated_at   :datetime
#

如果不执行大量代码,您将如何验证表单?

我的一般方法是否正确?

1 个答案:

答案 0 :(得分:0)

我认为更好的方法可能是嵌套字段方法。

您可以在此here (part 1)here (part 2)上取得良好的开端 正是你的情景,一个有问题和答案的调查。

对于验证,您需要提供有关所需验证类型的更多信息。