views:

556

answers:

4

I am currently developing a Rails application using a database that was designed before I was aware of Rails existence.
I have currently created some migrations to add some new tables and new columns to existing tables.

I would like to have the migrations to recreate the full database.

Which steps should I follow?
Should I create all the migrations by hand?

EDIT: I am interested in the database schema not in the database contents

+1  A: 

Short answer: Yes

Long answer: It depends on how the database was setup and how far it differs from your current one. Also, because I am assuming that the ID's are generated dynamically - if you move from one table to another make sure that all of your foreign keys are updated correctly.

Write a script that recreates the entire DB from the old data. If you posted your DB scheme and your new DB scheme I would be happy to help you out further :)

nlaq
The DB schemes will be identical. I have written the migrations for only a couple of new tables. Do I have to write the migrations for each one of the older tables.
hectorsq
+2  A: 

I think this will require some manual work.

You can start out by running rake db:schema:dump if you do not have the file db/schema.rb in your project. You probably already have a db/schema.rb file if you have been using migrations. That file will contain the ruby representation of the database you have configured for development. To get the ruby representation of another database pass in RAILS_ENV to the rake command (ie RAILS_ENV=production rake db:schema:dump)

You could then use that schema.rb file as a starting point to create new migrations that recreate the preexisting tables. When creating the new migration file make sure that it is named in such a way that it will be run prior to your other migrations.

Thomas Brice
+2  A: 

We had this exact issue when we ported a PHP application to rails. What we did is similar to tomtoday's suggestion. First we pointed the rails configuration to the current database. Then we did a rake db:schema:dump and copied the db/schema.rb file to something like db/schema_base.rb. Then you make your first migration loading that schema. For example:

class CreateTables < ActiveRecord::Migration
  def self.up
    `cp #{RAILS_ROOT}/db/schema_base.rb #{RAILS_ROOT}/db/schema.rb`
    Rake::Task['db:schema:load'].invoke
  end

  def self.down
  end
end

Just force this to be the first migration and you will be on your way. Then you start writing migrations to transform the database to be more compliant with the Rails way. We wrote migrations to properly rename id columns, foreign key relationships, table names, etc.
Remember that schema dump doesn't support foreign key constraints and triggers if you use those.

ScottD