class AddChoiceIndexToExerciseAnswers < ActiveRecord::Migration[5.2]
  def change
    add_column :exercise_answers, :choice_index, :integer, default: 1

    multi_questions = ExerciseQuestion.where(question_type: 1)
    multi_questions.includes(:exercise_choices, :exercise_answers).find_each do |question|
      exercise_answers = question.exercise_answers
      exercise_answers.find_each do |answer|
        choice_index = question.exercise_choices.pluck(:id).index(answer.exercise_choice_id).to_i + 1
        answer.update_column('choice_index', choice_index)
      end
      puts "multi_questions: #{question.id}"
    end

    ExerciseAnswer.joins(:exercise_question).where(exercise_questions: {question_type: 3}).update_all("choice_index = exercise_choice_id")
  end
end
