FIX: couldn't delete users who voted on a poll

FIX: couldn’t delete users who voted on a poll

From f402d0d74fffd73825a06640871cc3b72355fe48 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?R=C3=A9gis=20Hanol?= <regis@hanol.fr>
Date: Fri, 23 Nov 2018 11:45:53 +0100
Subject: [PATCH] FIX: couldn't delete users who voted on a poll


diff --git a/plugins/poll/plugin.rb b/plugins/poll/plugin.rb
index 001fd7d..6e6282e 100644
--- a/plugins/poll/plugin.rb
+++ b/plugins/poll/plugin.rb
@@ -359,6 +359,10 @@ after_initialize do
     end
   end
 
+  User.class_eval do
+    has_many :poll_votes, dependent: :delete_all
+  end
+
   validate(:post, :validate_polls) do |force = nil|
     return unless self.raw_changed? || force
 
@@ -427,10 +431,6 @@ after_initialize do
     PollVote.where(user_id: source_user.id).update_all(user_id: target_user.id)
   end
 
-  on(:user_destroyed) do |user|
-    PollVote.where(user_id: user.id).delete_all
-  end
-
   register_post_custom_field_type(DiscoursePoll::HAS_POLLS, :boolean)
 
   topic_view_post_custom_fields_whitelister { [DiscoursePoll::HAS_POLLS] }
diff --git a/plugins/poll/spec/requests/users_controller_spec.rb b/plugins/poll/spec/requests/users_controller_spec.rb
new file mode 100644
index 0000000..916085f
--- /dev/null
+++ b/plugins/poll/spec/requests/users_controller_spec.rb
@@ -0,0 +1,28 @@
+require "rails_helper"
+
+describe Admin::UsersController do
+
+  let(:admin) { Fabricate(:admin) }
+
+  before { sign_in(admin) }
+
+  describe '#destroy' do
+    let(:delete_me) { Fabricate(:user) }
+
+    context "user has voted" do
+      let!(:topic) { Fabricate(:topic, user: admin) }
+      let!(:post) { Fabricate(:post, topic: topic, user: admin, raw: "[poll]\n- a\n- b\n[/poll]") }
+
+      it "deletes the user" do
+        poll = Poll.last
+        PollVote.create!(user: delete_me, poll: poll, poll_option: poll.poll_options.first)
+
+        delete "/admin/users/#{delete_me.id}.json"
+        expect(response.status).to eq(200)
+        expect(User.exists?(id: delete_me.id)).to eq(false)
+        expect(PollVote.exists?(user_id: delete_me.id)).to eq(false)
+      end
+    end
+  end
+
+end

GitHub

2 Likes

This commit has been mentioned on Discourse Meta. There might be relevant details there: