# 执行示例 RAILS_ENV=production bundle exec rake migrate_course_student:student args=3835,2526,21950,1000 # args 第一个课程 course_id,第二个参数是学校school_id,第三个参数是部门id,第四个参数是迁移数量 # desc "同步学校的学生" namespace :migrate_course_student do if ENV['args'] course_id = ENV['args'].split(",")[0] # 对应课堂的id school_id = ENV['args'].split(",")[1] # 对应学校id department_id = ENV['args'].split(",")[2] # 对应部门id limit = ENV['args'].split(",")[3] # 限制导入的数量 end task :student => :environment do course = Course.find course_id users = User.joins(:user_extension).where(user_extensions: {school_id: school_id, department_id: department_id, identity: 1}).limit(limit) user_ids = [] users.each do |user| if user.student_id.present? && !course.students.exists?(user_id: user.id) begin CourseMember.create!(course_id: course_id, user_id: user.id, role: 4) user_ids << user.id rescue Exception => e Rails.logger(e.message) end end end CourseAddStudentCreateWorksJob.perform_later(course_id, user_ids) end end