class AddCourseidToToMembers < ActiveRecord::Migration
  def change
    add_column :members, :course_id, :int,:default => -1
    change_column_null(:members, :project_id, true)
    remove_index :members, name: 'index_members_on_user_id_and_project_id'
    add_index "members", ["user_id", "project_id","course_id"], :name => "index_members_on_user_id_and_project_id", :unique => true

    #couese_id不能直接设置为project_id
    #Member.where('project_id IN (SELECT id FROM projects WHERE project_type=1)').update_all("course_id = project_id")
    #Member.where('project_id IN (SELECT id FROM projects WHERE project_type=1)').update_all(project_id: -1)

    # 课程成员数据迁移
    Member.all.each do |member|
      project = Project.find_by_id(member.project_id)
      if project && project.project_type == 1
        member.course_id = project.course_extra.id
        member.project_id = -1
       member.save(:validate => false)
     end
    end
  end
end