diff --git a/app/controllers/poll_votes_controller.rb b/app/controllers/poll_votes_controller.rb index 4a15ae301..a2a5bf8c3 100644 --- a/app/controllers/poll_votes_controller.rb +++ b/app/controllers/poll_votes_controller.rb @@ -10,7 +10,7 @@ class PollVotesController < ApplicationController begin question_votes = @poll_question.poll_votes question_type = @poll_question.question_type - question_answer_id = params[:poll_answer_id] ? params[:poll_answer_id] : nil #该答案的id + question_answer_id = params[:poll_answer_id] ? params[:poll_answer_id] : -1 #该答案的id question_answer_text = params[:vote_text].present? ? params[:vote_text] : nil #其他选项的内容 user_votes = question_votes.find_current_vote("user_id",current_user.id) #当前用户的答案,可能有多个 # 当前用户的当前答案,如果已存在,当再次点击的时候,取消答案,即删除该答案 diff --git a/db/migrate/20191203040140_add_uniq_index_to_poll_votes.rb b/db/migrate/20191203040140_add_uniq_index_to_poll_votes.rb new file mode 100644 index 000000000..cdf94647a --- /dev/null +++ b/db/migrate/20191203040140_add_uniq_index_to_poll_votes.rb @@ -0,0 +1,16 @@ +class AddUniqIndexToPollVotes < ActiveRecord::Migration[5.2] + def change + remove_index :poll_votes, column: [:poll_question_id, :user_id] + + change_column_default :poll_votes, :poll_question_id, from: nil, to: -1 + PollVote.where(poll_answer_id: nil).update_all(poll_answer_id: -1) + + sql = %Q(delete from poll_votes where (poll_question_id, user_id, poll_answer_id) in + (select * from (select poll_question_id, user_id, poll_answer_id from poll_votes group by poll_question_id, user_id, poll_answer_id having count(*) > 1) a) + and id not in (select * from (select min(id) from poll_votes group by poll_question_id, user_id, poll_answer_id having count(*) > 1 order by id) b)) + ActiveRecord::Base.connection.execute sql + + add_index :poll_votes, [:poll_question_id, :user_id, :poll_answer_id], name: 'poll_answer_index', unique: true + + end +end