FIX: Add migration to set correct redemption_count (#12491)

FIX: Add migration to set correct redemption_count (#12491)

Redeeming email invites did not increase the redemption_count which let those invites in a weird state were they were both pending and redeemed.

diff --git a/app/models/invite.rb b/app/models/invite.rb
index da46b38..749bb85 100644
--- a/app/models/invite.rb
+++ b/app/models/invite.rb
@@ -212,7 +212,8 @@ class Invite < ActiveRecord::Base
       .joins("LEFT JOIN invited_users ON invites.id = invited_users.invite_id")
       .joins("LEFT JOIN users ON invited_users.user_id = users.id")
       .where(invited_by_id: inviter.id)
-      .where('redemption_count > max_redemptions_allowed OR expires_at < ?', Time.zone.now)
+      .where('redemption_count < max_redemptions_allowed')
+      .where('expires_at < ?', Time.zone.now)
       .order('invites.expires_at ASC')
   end
 
diff --git a/db/migrate/20210323142518_update_invites_redemption_count.rb b/db/migrate/20210323142518_update_invites_redemption_count.rb
new file mode 100644
index 0000000..2646799
--- /dev/null
+++ b/db/migrate/20210323142518_update_invites_redemption_count.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+class UpdateInvitesRedemptionCount < ActiveRecord::Migration[6.0]
+  def change
+    execute <<~SQL
+      WITH invite_counts AS (
+        SELECT invite_id, COUNT(*) count
+        FROM invited_users
+        GROUP BY invite_id
+      )
+      UPDATE invites
+      SET redemption_count = GREATEST(redemption_count, count)
+      FROM invite_counts
+      WHERE invites.id = invite_counts.invite_id
+    SQL
+  end
+end

GitHub sha: 2a4ddc62

This commit appears in #12491 which was approved by ZogStriP. It was merged by udan11.

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