Turning an existing database to a rails migration

by Melvin Ram

Q: Is there a way to make a migration from an existing database?

A. Yes, but you need to be more specific with this question because there are two ways.

The first approach will dump the schema of your existing database into a migration.

The second will dump the data as well. Why would you want to dump the data? If you’re moving machines or changing from a MySQL to a POSTGREs db, this might be useful.

Approach 1: Dump schema

Hint: Type in “rake -T” into your terminal. The will show you a list of all the rake tasks available to you. Everything you need is here.

Step 1: rake db:schema:dump   #this will dump the schema into a file called schema.rb

Step 2: rake db:schema:to_migration #this will turn your schema.rb file into a migration file

Approach 2: Dump schema + data

You’re going to need the YAMLdb plugin by Adam Wiggins at Heroku. To grab it from: http://github.com/adamwiggins/yaml_db/

Follow the instructions on the github page.

{ 3 comments… read them below or add one }

Brian February 25, 2009 at 7:44 am

Thanks for this. It was very helpful.

Mark Addinall March 20, 2010 at 7:29 pm

Not very helpful for me.

rake aborted!

Don’t know how to build task ‘db:schema:to_migration’

Running the rake -T show it is not available.

Is there a way to use an existing mySql database and get it into
a Rails environment easily? I dont care about the data, I just want
the models, migration stuff without doing it all by hand.

I have googled the web for about six hours now, and everything suggested
has not worked. Bummer.

Cheers,
Mark.

Nemo May 6, 2010 at 10:27 am

Looks like this is part of the auto_migrations plugin. See here: http://errtheblog.com/posts/65-automatically

Leave a Comment