class AddAccountToProjects < ActiveRecord::Migration[5.2]
  def up
    add_reference :projects, :account, foreign_key: true
    migrate_data_up
    remove_reference :projects, :user
  end

  def down
    add_reference :projects, :user, foreign_key: true
    migrate_data_down
    remove_reference :projects, :account
  end

  private

  class Project < ActiveRecord::Base
    belongs_to :account
    belongs_to :user
  end

  def migrate_data_up
    say "Setting Project#account.."
    
    Project.reset_column_information
    Project.find_each do |project|
      project.update!(account: project.user.account)
    end

    say "Done."
  end

  def migrate_data_down
    say "Setting Project#user.."

    Project.reset_column_information
    Project.find_each do |project|
      project.update!(user: project.account.users.first)
    end

    say "Done."
  end
end
