1

ランダムに生成された試験を作成するとき、すべての正解を配列に保存したいと考えています。これを行う理由は、試験を採点するときに、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
4

0 に答える 0