Files
nairobi/lib/tasks/polls.rake
Javi Martín b013a5b1b6 Add task to delete duplicate voters
Note that, since poll answers belong to a user and not to a voter, we
aren't doing anything regarding poll answers. This is a separate topic
that might be dealt with in a separate pull request.

Also note that, since there are no records belonging to poll voters, and
poll voters don't use `acts_as_paranoia` and don't have any callbacks on
destroy, it doesn't really matter whether we call `destroy!` or
`delete`. We're using `delete` so there are no unintended side-effects
that might affect voters with the same `user_id` and `poll_id` on
Consul Democracy installations customizing this behavior.
2024-06-26 15:41:44 +02:00

28 lines
1.0 KiB
Ruby

namespace :polls do
desc "Removes duplicate poll voters"
task remove_duplicate_voters: :environment do
logger = ApplicationLogger.new
logger.info "Removing duplicate voters in polls"
Tenant.run_on_each do
duplicate_ids = Poll::Voter.select(:user_id, :poll_id)
.group(:user_id, :poll_id)
.having("count(*) > 1")
.pluck(:user_id, :poll_id)
duplicate_ids.each do |user_id, poll_id|
voters = Poll::Voter.where(user_id: user_id, poll_id: poll_id)
voters.excluding(voters.first).each do |voter|
voter.delete
tenant_info = " on tenant #{Tenant.current_schema}" unless Tenant.default?
logger.info "Deleted duplicate record with ID #{voter.id} " \
"from the #{Poll::Voter.table_name} table " \
"with user_id #{user_id} " \
"and poll_id #{poll_id}" + tenant_info.to_s
end
end
end
end
end