FIX: De-duplicate poll vote on user merge (#22107)

When merging users, polls may error out if the source and target users have both voted on the same poll before. 😢 

There is no constraint on the `poll_votes` table either to support this. Ideally a composite primary key can be used `(poll_id, user_id)`, but alas there is no support yet, which is probably why it wasn't created in the first place.

This fix ensures that merging is successful by only keeping the target poll votes if duplicates exist.

This fix also runs a migration on older poll votes where failed merges would have caused a single user to have voted twice on a single poll. e.g. this weird edge case
This commit is contained in:
Natalie Tay
2023-06-15 11:18:51 +08:00
committed by GitHub
parent ec31eb4c7b
commit fcaefc9f2f
4 changed files with 95 additions and 1 deletions

View File

@ -0,0 +1,18 @@
# frozen_string_literal: true
class DeleteDuplicatePollVotes < ActiveRecord::Migration[7.0]
def up
execute <<~SQL
DELETE FROM poll_votes
WHERE (poll_id, user_id, updated_at) NOT IN (
SELECT poll_id, user_id, MAX(updated_at)
FROM poll_votes
GROUP BY poll_id, user_id
)
SQL
end
def down
raise ActiveRecord::IrreversibleMigration
end
end