Posted about 2 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.

Copy
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.

Copy
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.

Copy
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

Copy
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):

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

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:

Avatar
Emanuel De
Last edit:
21 days 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 cookies to improve usability and analyze traffic.
Accept or learn more