Migrating from a Legacy Datasource
May 01, 2009 08:32PM
Refactoring a project in Rails can be a handful, especially when the original database does not conform to Rails standards. Lately, I've found it much quicker to simply redesign the data model, and migrate the data from the old database.
I've had to tackle this problem a couple of times now, and feel like I've refined the process a great deal. I don't know if this is the correct way of doing things, I'm just saying, it works for me.
Step #1 - Map the legacy database
- Create a new file under config/initializers called legacy.rb
- Create a new module, we'll call it "Legacy"
module Legacy
end - Map your original database as best you can to rails models.
module Legacy
class ActiveRecordLegacy < ActiveRecord::Base
self.establish_connection(
:adapter => 'mysql',
:host => 'localhost',
:username => 'username',
:password => 'password',
:database => 'legacy_database'
)
end
class LegacyTable < ActiveRecordLegacy
set_table_name :legacy_table
set_primary_key :LegacyTableID
end
end
Step #2 - Create your migration script
- Create a new file model under app/models called migrate.rb
class Migrate
end - Fill in your migration steps!
class Migrate
def self.run
Migrate.migrate_legacy_table()
end
def self.migrate_legacy_table
Legacy::LegacyTable.find(:all).each { |record|
# Do some nifty migrations here
}
end
end - Load up the rails console: ruby ./script/console
>> Migrate.run
Again, I don't know if this is the "correct" method, it's just how I do things.
-Butch