我有一个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.eachdo|answer|I得到的答案==
["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
如果您改变表单的结构方式,会简单得多。
answer[1].keys.first.sub("answer_", '').to_i
会给你3个例子["question_1",{"answer_3"=>"5"}],然后你可以将其与问题模型中的correct_answer_number进行比较。
我不确定与"answer_x"相关的值是多少?我认为这不是答案(如1,2,3或4),因为它是5,而你只有4个可能的答案,所以我认为5是这个问题的实际答案,并忽略了它。