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
.
Copydata_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.
Copyclass 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
.
Copyclass 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
Copyclass 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):
Copyrails 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.