Note that there are some explanatory texts on larger screens.

plurals
  1. PObefore_create callback generates random array
    text
    copied!<p>When I create a randomly generate exam I would like to store all the correct answer in an array. The reason that I am doing this is because when I grade the exam I would like to see if the answer is correct by matching the user_answer with the same element in the correct_answer array. Unfortunately, when i use a callback its putting the correct answers in a random order where I cannot match them appropriately. </p> <pre><code> ##controller## class ExamsController &lt; 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 &lt;&lt; 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 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload