当我创建一个随机生成的考试时,我想将所有正确答案存储在一个数组中。我这样做的原因是因为当我对考试进行评分时,我想通过将user_answer与correct_answer数组中的相同元素相匹配来查看答案是否正确。不幸的是,当我使用回调时,它会以随机顺序输入正确答案,而我无法正确匹配它们。
##controller##
class ExamsController < ApplicationController
def create
exam = current_user.exams.create!(test_bank_questions: TestBankQuestion.all.sample(5))
exam.answers
redirect_to exam_question_path(exam, '1')
end
end
#####Model######
class Exam
include Mongoid::Document
before_create :answers
field :user_answer, type: Array, default: []
field :correct_answers_ids, type: Array, default: []
belongs_to :user
has_and_belongs_to_many :test_bank_questions
#### This is where my problem is ####
#I am trying to get all the id's of the correct answer
#and put them in an array when the object is created
def answers
exam_questions = self.test_bank_questions
exam_questions.each do |question|
answer_choices = question.answer_choices
answer_choices.each do |choice|
if choice.correct_choice == true
self.correct_answers_ids << choice.id.to_s
end
end
end
return correct_answers_ids
end
end
####Model ####
class TestBankQuestion
include Mongoid::Document
field :question_url, type: String
embeds_many :answer_choices
has_and_belongs_to_many :exams
end
###Model ###
class AnswerChoice
include Mongoid::Document
field :choice_url, type: String, default: []
field :correct_choice, type: Boolean, default: []
embedded_in :test_bank_question
end