FIX: update flair group of all members if primary group setting changed. (#14762)

FIX: update flair group of all members if primary group setting changed. (#14762)

Previously, if we enable the primary_group setting on a group then the flair_group_id of its’ members are not affected.

diff --git a/app/models/group.rb b/app/models/group.rb
index 374058f..889df66 100644
--- a/app/models/group.rb
+++ b/app/models/group.rb
@@ -979,23 +979,26 @@ class Group < ActiveRecord::Base
         /*where*/
       SQL
 
-      builder = DB.build(sql)
-      builder.where(<<~SQL, id: id)
-        id IN (
-          SELECT user_id
-          FROM group_users
-          WHERE group_id = :id
-        )
-      SQL
+      [:primary_group_id, :flair_group_id].each do |column|
+        builder = DB.build(sql)
+        builder.where(<<~SQL, id: id)
+          id IN (
+            SELECT user_id
+            FROM group_users
+            WHERE group_id = :id
+          )
+        SQL
 
-      if primary_group
-        builder.set("primary_group_id = :id")
-      else
-        builder.set("primary_group_id = NULL")
-        builder.where("primary_group_id = :id")
-      end
+        if primary_group
+          builder.set("#{column} = :id")
+          builder.where("#{column} IS NULL") if column == :flair_group_id
+        else
+          builder.set("#{column} = NULL")
+          builder.where("#{column} = :id")
+        end
 
-      builder.exec
+        builder.exec
+      end
     end
   end
 
diff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rb
index c72f6f8..7f4aed0 100644
--- a/spec/models/group_spec.rb
+++ b/spec/models/group_spec.rb
@@ -198,12 +198,19 @@ describe Group do
   end
 
   describe '#primary_group=' do
-    it "updates all members' #primary_group" do
+    before do
       group.add(user)
+    end
 
+    it "updates all members' #primary_group" do
       expect { group.update(primary_group: true) }.to change { user.reload.primary_group }.from(nil).to(group)
       expect { group.update(primary_group: false) }.to change { user.reload.primary_group }.from(group).to(nil)
     end
+
+    it "updates all members' #flair_group" do
+      expect { group.update(primary_group: true) }.to change { user.reload.flair_group }.from(nil).to(group)
+      expect { group.update(primary_group: false) }.to change { user.reload.flair_group }.from(group).to(nil)
+    end
   end
 
   describe '#title=' do

GitHub sha: deee715a2cbd7668b5f94f1a79e5012de70779f1

This commit appears in #14762 which was approved by eviltrout. It was merged by vinothkannans.