class Ecs::CreateMajorManagerService < ApplicationService Error = Class.new(StandardError) MAJOR_MANAGER_COUNT_LIMIT = 5 # 专业管理员数量限制 attr_reader :major_school, :user_ids def initialize(major_school, user_ids) @major_school = major_school @user_ids = user_ids end def call raise Error, '示例专业不能添加管理员' if major_school.template_major? @user_ids = User.where(id: user_ids).pluck(:id) if major_school.ec_major_school_users.exists?(user_id: user_ids) raise Error, '所选用户中存在该专业的管理员' end if major_school.ec_major_school_users.count + user_ids.count > MAJOR_MANAGER_COUNT_LIMIT raise Error, "该专业管理员数量超过上限(#{MAJOR_MANAGER_COUNT_LIMIT}人)" end ActiveRecord::Base.transaction do user_ids.each do |user_id| major_school.ec_major_school_users.create!(user_id: user_id) end end end end