使用哈希键和值

时间:2012-02-29 00:54:21

标签: ruby-on-rails ruby ruby-on-rails-3 postgresql

我有一个模型QuizAttempt,它将检查测验的结果。我期待循环每个提交的答案并检查问题ID,如果提供的答案是正确的。我正在寻找一些指导......

class QuizAttempt < ActiveRecord::Base
  belongs_to :user
  belongs_to :quiz

  validates_presence_of :quiz, :user
  validate :check_result

  attr_accessor :questions, :submitted_answers

  private

  def self.create_for_user_and_answers!(user, answers)
    self.new(:user => user).tap do |q| 
      q.submitted_answers = answers
      q.questions = []
      answers.each{|k, v| q.questions = q.questions << Question.find(k.gsub(/[^0-9]/i, '').to_i) }
    end
  end

  def check_result
    if submitted_answers
      unless submitted_answers.keys.length == quiz.easy_questions + quiz.moderate_questions + quiz.hard_questions
        self.errors.add(:submitted_answers, "must be provided for each question")
      end
    else
      self.errors.add(:submitted_answers, "must be provided")
    end

    return false unless self.errors.empty?

    score = 0
    submitted_answers.each do |answer|
      #check the answers and score + 1 if correct
    end
    self.total_questions = submitted_answers.length
    self.passed_questions = score
    self.passed = percentage_score >= quiz.pass_percentage
  end

  public

  def percentage_score
    (passed_questions / total_questions.to_f * 100).to_i
  end

end

提交的答案采用(嵌套?)哈希的形式,从带有单选按钮的表单返回

{"question_1"=>{"answer_3"=>"5"}, "question_2"=>{"answer_2"=>"4"}}

但是当我按照上面的QuizAttempt模型循环它们时,即。 submitted_answers.each do | answer |我得到答案==

["question_1", {"answer_3"=>"5"}]

我想根据下面的问题模型检查这些答案

class Question < ActiveRecord::Base
  belongs_to :quiz

  validates :question, :presence => true, :length => {:minimum => 3, :maximum => 254}
  validates :answer_1, :answer_2, :answer_3, :answer_4, :presence => true, :length => {:maximum => 254}
  validates :rank, :presence => true, :numericality => { :only_integer => true, :greater_than => 0, :less_than => 4 }
  validate :only_one_answer_correct  

  #has boolean values answer_1_correct, answer_2_correct, answer_3_correct, answer_4_correct

  def correct_answer_number
    (1..4).each{|i| return i if send("answer_#{i}_correct")}
  end
end

1 个答案:

答案 0 :(得分:1)

如果你改变了表单的结构方式,那会更简单。

answer[1].keys.first.sub("answer_", '').to_i

将根据您的示例[“question_1”,{“answer_3”=&gt;“5”}]给出3,然后您可以将其与问题模型中的correct_answer_number进行比较。

我不确定与“answer_x”相关的值是什么?我认为它不是答案(如在1,2,3或4中),因为它是5,你只有4个可能的答案,所以我认为5是问题的实际答案而忽略了它。