FIX: Delete the votes on user removal (#59)

FIX: Delete the votes on user removal (#59)

There are some assumptions in the code that vote.user exists. It makes sense to boop the votes out of existence when their owner is destroyed.

diff --git a/db/post_migrate/20201003141123_remove_votes_of_deleted_users.rb b/db/post_migrate/20201003141123_remove_votes_of_deleted_users.rb
new file mode 100644
index 0000000..66e5f87
--- /dev/null
+++ b/db/post_migrate/20201003141123_remove_votes_of_deleted_users.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+class RemoveVotesOfDeletedUsers < ActiveRecord::Migration[6.0]
+  def up
+    DB.exec <<~SQL
+      DELETE FROM discourse_voting_votes
+      WHERE user_id IN (
+        SELECT votes.user_id
+        FROM discourse_voting_votes votes
+        LEFT JOIN users ON users.id = votes.user_id
+        WHERE users.id IS NULL
+      )
+    SQL
+  end
+
+  def down
+    raise ActiveRecord::IrreversibleMigration
+  end
+end
diff --git a/lib/discourse_voting/user_extension.rb b/lib/discourse_voting/user_extension.rb
index d8814a1..81dc28a 100644
--- a/lib/discourse_voting/user_extension.rb
+++ b/lib/discourse_voting/user_extension.rb
@@ -3,7 +3,7 @@
 module DiscourseVoting
   module UserExtension
     def self.prepended(base)
-      base.has_many :votes, class_name: 'DiscourseVoting::Vote'
+      base.has_many :votes, class_name: 'DiscourseVoting::Vote', dependent: :destroy
     end
   end
 end

GitHub sha: b92385aa

This commit appears in #59 which was approved by davidtaylorhq. It was merged by CvX.