Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to migrate legacy PHP mysql data to new Rails data model?

I'm trying to port an old PHP app to Rails. I dumped the legacy mysql tables and uploaded them to the server where the new rails app is running. What's the best way to migrate the data from the old legacy tables into the new Rails model? I could write a PHP script to spit out everything in ruby and then use that to populate seed.rb, but it seems like there should be an easier way to do achieve this.

New app is RoR 3.0.9, and database is still mysql.

like image 956
bjork24 Avatar asked Jan 19 '23 02:01

bjork24


1 Answers

I would write a rake task to wire up the old tables and dump them to the new db. Something like this:

# config/database.yml
legacy_db:
  adapter: mysql
  username: foo
  password: bar

# lib/tasks/import.rake
namespace :import do
  desc 'import the legacy db data'
  task :legacy => :environment do

    # connect to legacy db
    class OldDb < ActiveRecord::Base
      establish_connection :legacy_db
    end

    # define classes for legacy tables
    class OldUser < OldDb
      set_table_name 'user'
      set_primary_key 'user_id'
    end
    # ...do this for all your old tables

    # import from old models to new models
    OldUser.all.each do |u|
      User.create(
        :user_name  => u.login_name
        :created_at => Time.parse(u.account_opened_date)
        # etc....
      )
    end

  end
end

and call with: RAILS_ENV=production bundle exec rake import:legacy

like image 94
Unixmonkey Avatar answered Mar 17 '23 10:03

Unixmonkey