FIX: Reset flair group if user is removed from group (#17862)

The flair used to stay set even if the user was removed from the group.
This commit is contained in:
Bianca Nenciu 2022-08-12 15:45:09 +03:00 committed by GitHub
parent 69664d2153
commit 4b70594173
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 27 additions and 6 deletions

View File

@ -8,7 +8,7 @@ class GroupUser < ActiveRecord::Base
after_destroy :grant_other_available_title after_destroy :grant_other_available_title
after_save :set_primary_group after_save :set_primary_group
after_destroy :remove_primary_group, :recalculate_trust_level after_destroy :remove_primary_and_flair_group, :recalculate_trust_level
before_create :set_notification_level before_create :set_notification_level
after_save :grant_trust_level after_save :grant_trust_level
@ -84,10 +84,14 @@ class GroupUser < ActiveRecord::Base
user.update!(primary_group: group) if group.primary_group user.update!(primary_group: group) if group.primary_group
end end
def remove_primary_group def remove_primary_and_flair_group
return if user.primary_group_id != group_id
return if self.destroyed_by_association&.active_record == User # User is being destroyed, so don't try to update return if self.destroyed_by_association&.active_record == User # User is being destroyed, so don't try to update
user.update_attribute(:primary_group_id, nil)
updates = {}
updates[:primary_group_id] = nil if user.primary_group_id == group_id
updates[:flair_group_id] = nil if user.flair_group_id == group_id
user.update(updates) if updates.present?
end end
def grant_other_available_title def grant_other_available_title

View File

@ -0,0 +1,16 @@
# frozen_string_literal: true
class ResetFlairGroupIdIfNotGroupMember < ActiveRecord::Migration[7.0]
def change
execute <<~SQL
UPDATE users
SET flair_group_id = NULL
WHERE flair_group_id IS NOT NULL AND NOT EXISTS (
SELECT 1
FROM group_users
WHERE group_users.user_id = users.id
AND group_users.group_id = users.flair_group_id
)
SQL
end
end

View File

@ -226,8 +226,8 @@ RSpec.describe GroupUser do
describe '#destroy!' do describe '#destroy!' do
fab!(:group) { Fabricate(:group) } fab!(:group) { Fabricate(:group) }
it "removes `primary_group_id` and exec `match_primary_group_changes` method on user model" do it "removes `primary_group_id`, `flair_group_id` and exec `match_primary_group_changes` method on user model" do
user = Fabricate(:user, primary_group: group) user = Fabricate(:user, primary_group: group, flair_group: group)
group_user = Fabricate(:group_user, group: group, user: user) group_user = Fabricate(:group_user, group: group, user: user)
user.expects(:match_primary_group_changes).once user.expects(:match_primary_group_changes).once
@ -235,6 +235,7 @@ RSpec.describe GroupUser do
user.reload user.reload
expect(user.primary_group_id).to be_nil expect(user.primary_group_id).to be_nil
expect(user.flair_group_id).to be_nil
end end
end end
end end