diff --git a/app/controllers/admin/groups_controller.rb b/app/controllers/admin/groups_controller.rb index 920cc34955d..4b062cfc25f 100644 --- a/app/controllers/admin/groups_controller.rb +++ b/app/controllers/admin/groups_controller.rb @@ -66,6 +66,7 @@ class Admin::GroupsController < Admin::AdminController group.title = group.automatic ? nil : title if group.save + Group.reset_counters(group.id, :group_users) render_serialized(group, BasicGroupSerializer) else render_json_error group @@ -101,6 +102,8 @@ class Admin::GroupsController < Admin::AdminController group.group_users.where(user_id: user.id).update_all(owner: true) end + Group.reset_counters(group.id, :group_users) + render json: success_json end @@ -111,6 +114,8 @@ class Admin::GroupsController < Admin::AdminController user = User.find(params[:user_id].to_i) group.group_users.where(user_id: user.id).update_all(owner: false) + Group.reset_counters(group.id, :group_users) + render json: success_json end diff --git a/app/jobs/regular/automatic_group_membership.rb b/app/jobs/regular/automatic_group_membership.rb index 738d0db4ead..e66942fbce0 100644 --- a/app/jobs/regular/automatic_group_membership.rb +++ b/app/jobs/regular/automatic_group_membership.rb @@ -13,15 +13,17 @@ module Jobs domains = group.automatic_membership_email_domains.gsub('.', '\.') - User.where("email ~* '@(#{domains})$' and users.id not in ( - select user_id from group_users where group_users.group_id = ? - )", group_id).find_each do |user| + User.where("email ~* '@(#{domains})$'") + .where("users.id NOT IN (SELECT user_id FROM group_users WHERE group_users.group_id = ?)", group_id) + .find_each do |user| begin group.add(user) rescue ActiveRecord::RecordNotUnique, PG::UniqueViolation # we don't care about this end end + + Group.reset_counters(group.id, :group_users) end end diff --git a/app/jobs/scheduled/ensure_db_consistency.rb b/app/jobs/scheduled/ensure_db_consistency.rb index b778842122b..aa5b3b8e36f 100644 --- a/app/jobs/scheduled/ensure_db_consistency.rb +++ b/app/jobs/scheduled/ensure_db_consistency.rb @@ -5,7 +5,7 @@ module Jobs def execute(args) UserVisit.ensure_consistency! - Group.refresh_automatic_groups! + Group.ensure_consistency! Notification.ensure_consistency! UserAction.ensure_consistency! TopicFeaturedUsers.ensure_consistency! diff --git a/app/models/group.rb b/app/models/group.rb index 3acf120e7dc..db69406648a 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -217,6 +217,17 @@ class Group < ActiveRecord::Base group end + def self.ensure_consistency! + reset_all_counters + refresh_automatic_groups + end + + def self.reset_all_counters + Group.pluck(:id).each do |group_id| + Group.reset_counters(group_id, :group_users) + end + end + def self.refresh_automatic_groups!(*args) if args.length == 0 args = AUTO_GROUPS.keys