You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
educoder/db/migrate/20191203124903_add_index_to...

17 lines
977 B

5 years ago
class AddIndexToExerciseChoice < ActiveRecord::Migration[5.2]
def change
change_column_default :exercise_answers, :exercise_choice_id, from: nil, to: -1
ExerciseAnswer.where(exercise_choice_id: nil).update_all(exercise_choice_id: -1)
sql = %Q(delete from exercise_answers where (exercise_question_id, user_id, exercise_choice_id) in
(select * from (select exercise_question_id, user_id, exercise_choice_id from exercise_answers group by exercise_question_id, user_id, exercise_choice_id having count(*) > 1) a)
and id not in (select * from (select min(id) from exercise_answers group by exercise_question_id, user_id, exercise_choice_id having count(*) > 1 order by id) b))
ActiveRecord::Base.connection.execute sql
add_index :exercise_answers, [:exercise_question_id, :user_id, :exercise_choice_id], name: 'exercise_choice_index', unique: true
5 years ago
remove_index :exercise_answers, name: :index_on_question_id_user_id
5 years ago
end
end