class Competitions::CreatePersonalTeamService < ApplicationService Error = Class.new(StandardError) attr_reader :competition, :user def initialize(competition, user) @competition = competition @user = user end def call raise Error, '个人赛才能报名' unless competition.personal? is_teacher = user.is_teacher? raise Error, '本竞赛的参赛者限定为:学生' if is_teacher && competition.teacher_enroll_forbidden? raise Error, '本竞赛的参赛者限定为:教师' if !is_teacher && competition.member_enroll_forbidden? enrolled = competition.competition_teams.exists?(user_id: user.id) multiple_limited = (is_teacher && competition.teacher_multiple_limited?) || (!is_teacher && competition.member_multiple_limited?) raise Error, '您已报名该竞赛' if enrolled && multiple_limited ActiveRecord::Base.transaction do team = competition.competition_teams.create!(name: user.show_name, user_id: user.id) team.team_members.create!(competition_id: competition, user_id: user.id, role: 1, is_teacher: is_teacher) end end end