You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
educoder/app/services/ecs/import_student_service.rb

35 lines
989 B

6 years ago
class Ecs::ImportStudentService < ApplicationService
Error = Class.new(StandardError)
attr_reader :ec_year, :params
6 years ago
def initialize(ec_year, params)
@ec_year = ec_year
@params = params
6 years ago
end
def call
raise Error, '文件不存在' if params[:file].blank? || !params[:file].is_a?(ActionDispatch::Http::UploadedFile)
6 years ago
excel = Ecs::ImportStudentExcel.new(params[:file].path)
6 years ago
success_count = 0
5 years ago
EcYearStudent.bulk_insert(:ec_year_id, :student_id, :name, :created_at, :updated_at) do |worker|
6 years ago
excel.read_each do |student_id, name|
success_count += 1
student = ec_year.ec_year_students.find_by(student_id: student_id)
if student.present?
student.update!(name: name)
next
end
5 years ago
worker.add(ec_year_id: ec_year.id, student_id: student_id, name: name)
6 years ago
end
end
success_count
rescue BaseImportExcel::Error => ex
raise Error, ex.message
end
end