class Ecs::CreateCourseService < ApplicationService Error = Class.new(StandardError) attr_reader :ec_year, :params def initialize(ec_year, params) @ec_year = ec_year @params = params end def call name = params[:name].to_s.strip if ec_year.ec_courses.exists?(name: name) raise Error, '课程名称重复' end ec_course = nil ActiveRecord::Base.transaction do ec_course = ec_year.ec_courses.create!(name: name) create_default_score_levels!(ec_course) end ec_course end private def create_default_score_levels!(ec_course) EcScoreLevel.bulk_insert(:ec_course_id, :score, :level, :position) do |worker| [ { ec_course_id: ec_course.id, score: 90, level: '优秀', position: 1 }, { ec_course_id: ec_course.id, score: 80, level: '良好', position: 2 }, { ec_course_id: ec_course.id, score: 70, level: '中等', position: 3 }, { ec_course_id: ec_course.id, score: 60, level: '及格', position: 4 }, { ec_course_id: ec_course.id, score: 60, level: '不及格', position: 5 }, ].each do |attributes| worker.add attributes end end end end