diff --git a/app/controllers/admin/groups_controller.rb b/app/controllers/admin/groups_controller.rb index 62653c427..920cc3495 100644 --- a/app/controllers/admin/groups_controller.rb +++ b/app/controllers/admin/groups_controller.rb @@ -28,28 +28,7 @@ class Admin::GroupsController < Admin::AdminController if group.present? users = (params[:users] || []).map {|u| u.downcase} user_ids = User.where("username_lower in (:users) OR email IN (:users)", users: users).pluck(:id) - - if user_ids.present? - Group.exec_sql("INSERT INTO group_users - (group_id, user_id, created_at, updated_at) - SELECT #{group.id}, - u.id, - CURRENT_TIMESTAMP, - CURRENT_TIMESTAMP - FROM users AS u - WHERE u.id IN (#{user_ids.join(', ')}) - AND NOT EXISTS(SELECT 1 FROM group_users AS gu - WHERE gu.user_id = u.id AND - gu.group_id = #{group.id})") - - if group.primary_group? - User.where(id: user_ids).update_all(primary_group_id: group.id) - end - - if group.title.present? - User.where(id: user_ids).update_all(title: group.title) - end - end + group.bulk_add(user_ids) if user_ids.present? end render json: success_json diff --git a/app/models/group.rb b/app/models/group.rb index a508335a7..148b1e9e8 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -335,6 +335,31 @@ class Group < ActiveRecord::Base self.find_by(incoming_email: Email.downcase(email)) end + def bulk_add(user_ids) + if user_ids.present? + Group.exec_sql("INSERT INTO group_users + (group_id, user_id, created_at, updated_at) + SELECT #{self.id}, + u.id, + CURRENT_TIMESTAMP, + CURRENT_TIMESTAMP + FROM users AS u + WHERE u.id IN (#{user_ids.join(', ')}) + AND NOT EXISTS(SELECT 1 FROM group_users AS gu + WHERE gu.user_id = u.id AND + gu.group_id = #{self.id})") + + if self.primary_group? + User.where(id: user_ids).update_all(primary_group_id: self.id) + end + + if self.title.present? + User.where(id: user_ids).update_all(title: self.title) + end + end + true + end + protected def name_format_validator