class AddAttendanceToCourseModule < ActiveRecord::Migration[5.2]
  def change
    Course.all.each do |course|
      unless course.course_modules.exists?(module_type: "attendance")
        atta_position = course.course_modules.find_by(module_type: 'course_group')&.position.to_i
        attendance_position = atta_position != 0 ? (atta_position + 1) : 14
        course.course_modules.where("position >= #{attendance_position}").update_all("position = position + 1")
        if course.is_end
          course.course_modules << CourseModule.new(module_type: "attendance", hidden: 1, module_name: "签到", position: attendance_position)
        else
          course.course_modules << CourseModule.new(module_type: "attendance", hidden: 0, module_name: "签到", position: attendance_position)
        end
      end
    end
  end
end
