试卷的答案增加索引

dev_forge
cxt 5 years ago
parent e93cb92ade
commit 7dce5948c2

@ -4,7 +4,6 @@ class ExerciseAnswersController < ApplicationController
include ExercisesHelper include ExercisesHelper
def create #每一次答案的点击,请求一次,实训题不在这里回答 def create #每一次答案的点击,请求一次,实训题不在这里回答
ActiveRecord::Base.transaction do
begin begin
q_type = @exercise_question.question_type #试卷的类型 q_type = @exercise_question.question_type #试卷的类型
choice_id = params[:exercise_choice_id].present? ? params[:exercise_choice_id] : "" choice_id = params[:exercise_choice_id].present? ? params[:exercise_choice_id] : ""
@ -31,8 +30,8 @@ class ExerciseAnswersController < ApplicationController
ea_ids = ea.pluck(:exercise_choice_id) ea_ids = ea.pluck(:exercise_choice_id)
common_answer_ids = choice_ids & ea_ids #已经存在的试卷选项id common_answer_ids = choice_ids & ea_ids #已经存在的试卷选项id
new_ids = choice_ids - common_answer_ids # 新增的id new_ids = (choice_ids - common_answer_ids).uniq # 新增的id
old_ids = ea_ids - common_answer_ids #没有选择的,则删掉 old_ids = (ea_ids - common_answer_ids).uniq #没有选择的,则删掉
if new_ids.size > 0 if new_ids.size > 0
new_ids.each do |e| new_ids.each do |e|
answer_option = { answer_option = {
@ -84,7 +83,6 @@ class ExerciseAnswersController < ApplicationController
raise ActiveRecord::Rollback raise ActiveRecord::Rollback
end end
end end
end
private private

@ -0,0 +1,17 @@
class AddUniqIndexToExerciseAnswer < ActiveRecord::Migration[5.2]
def change
remove_index :exercise_answers, column: [:exercise_question_id, :user_id]
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
end
end
Loading…
Cancel
Save