move code for bulk adding users to a group from controller to model

This commit is contained in:
Neil Lalonde 2016-02-18 14:03:00 -05:00
parent 8a1a9f60a2
commit 283ff4c7f8
2 changed files with 26 additions and 22 deletions

View File

@ -28,28 +28,7 @@ class Admin::GroupsController < Admin::AdminController
if group.present? if group.present?
users = (params[:users] || []).map {|u| u.downcase} users = (params[:users] || []).map {|u| u.downcase}
user_ids = User.where("username_lower in (:users) OR email IN (:users)", users: users).pluck(:id) user_ids = User.where("username_lower in (:users) OR email IN (:users)", users: users).pluck(:id)
group.bulk_add(user_ids) if user_ids.present?
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
end end
render json: success_json render json: success_json

View File

@ -335,6 +335,31 @@ class Group < ActiveRecord::Base
self.find_by(incoming_email: Email.downcase(email)) self.find_by(incoming_email: Email.downcase(email))
end 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 protected
def name_format_validator def name_format_validator