How to mount a legacy database to migrate data

Updated . Posted . Visible to the public.

There are many approaches out there how you can import data from a legacy application to a new application. Here is an approach which opens two database connections and uses active record for the legacy system, too:

1. Add you database information to you config/database.yml.

data_migration:
  database: your_application_data_migration

2. Create a separate application record for the data migration, e.g. in app/data_migration/migration_record.rb. You will need to create an app/data_migration.rb class first.

class DataMigration::MigrationRecord < ActiveRecord::Base

  self.abstract_class = true
  establish_connection(:data_migration)
  
end

3. Inherit from this class in the migration models, e.g. app/data_migration/user.rb.

class DataMigration::MigrationUser < DataMigration::MigrationRecord

  self.table_name = 'zz_1234_0' # you will need this if the table name is not data_migration_migration_users
  self.primary_key = 'data_id' # you will need this if the primary key is not id

  alias_attribute :title, :c1254
  alias_attribute :first_name, :c1255
  alias_attribute :last_name, :c1256
  alias_attribute :email, :c1257
  alias_attribute :phone, :c1258

end

4. Extend your app/models/data_migration.rb

class DataMigration

  def run
    migrate_users
  end

  def migrate_users
    DataMigration::MigrationUser.find_each do |migration_user|
      User.create!(
        title: migration_user.title,
        first_name: migration_user.first_name,
        last_name: migration_user.last_name,
        email: migration_user.email,
        phone: migration_user.phone
      )
    end
  end
  
end  

Now the best idea is to test this in the rails sandbox (so your development data stay untouched):

rails console --sandbox
2.4.1 :003 > DataMigration.new.run

Keep in mind our best practices for data migrations.

Last edit
Tobias Kraze
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2017-08-14 11:19)