class AddCourseMemberId < ActiveRecord::Migration[5.2]
  def change
    add_column :student_graduation_topics, :course_member_id, :integer
    add_index :student_graduation_topics, :course_member_id

    StudentGraduationTopic.find_each do |student|
      course_member = CourseMember.where(course_id: student.course_id, user_id: student.user_id,
      role: 4).first
      student.update_column("course_member_id", course_member.try(:id)) if course_member.present?
    end

    add_column :teacher_course_groups, :course_member_id, :integer
    add_index :teacher_course_groups, :course_member_id

    TeacherCourseGroup.find_each do |teacher|
      course_member = CourseMember.where(course_id: teacher.course_id, user_id: teacher.user_id,
                                         role: [1, 2, 3]).first
      teacher.update_column("course_member_id", course_member.try(:id)) if course_member.present?
    end
  end
end
