class AddColumnToStudentWorks < ActiveRecord::Migration
  def change
    add_column :student_works, :work_score, :float
    count = StudentWork.all.count / 30 + 2
    transaction do
      for i in 1 ... count do i
        StudentWork.page(i).per(30).each do |sw|
          if sw.homework_common && sw.homework_common.teacher_priority == 0
            unless sw.final_score.nil?
              score = sw.final_score - sw.absence_penalty - sw.late_penalty
              sw.update_column('work_score', score < 0 ? 0 : score)
            end
          elsif sw.homework_common && sw.homework_common.teacher_priority == 1
            unless sw.final_score.nil?
              if sw.teacher_score
                sw.update_column('work_score', sw.teacher_score)
              else
                score = sw.final_score - sw.absence_penalty - sw.late_penalty
                sw.update_column('work_score', score < 0 ? 0 : score)
              end
            end
          end
        end
      end
    end
  end
end
