0
我有一個模型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