私は、クイズの結果をチェックするモデルの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 |答え|私は答えの==
["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