Posted over 3 years ago. Visible to the public.

How to mount a legacy database to migrate data

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:, 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 >

Keep in mind our best practices for data migrations.

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Emanuel De
Last edit:
over 1 year ago
by Besprechungs-PC
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more