Starting a Ruby on Rails project from existing data

Ideally when you are starting a Ruby on Rails project you’re starting from scratch and most tutorials and guides you’ll find on the Internet assume this. I found very little information about starting a project from existing data and I thought I’d share the solution which I found and consider the simplest.

So, we’re supposing the already existing database is called library_development and you can access it with the joe user having password secret and that you have created a new rails app which should be able to connect to a mysql database.

The first thing you should do is configure your database, by editing the development section of config/database.yml to look something like the following (please note that the bolded values are the same as above):

adapter: mysql2
encoding: utf8
reconnect: false
database: library_development
pool: 5
username: joe
password: secret
socket: /var/run/mysqld/mysqld.sock

You are now ready to dump the schema (structure) of your database by issuing:

rake db:schema:dump

This will generate db/schema.rb. Now you need to copy the contents of this file and save it as your first migration. So let’s create an empty migration file. Run:

rails generate migration create_database_structure

Move the contents of db/schema.rb into the up method of this first migration. Now whenever you will run your migration the database’s structure will be created. But the database will still be empty. So let’s populate it with your existing data.

I found the best option for this task to be the yaml_db gem. Let’s add it to your project. Edit your Gemfile and add the following line:

gem 'yaml_db'

Now run:

bundle install

The yaml_db gem should now be installed. Try running:

rake db:data:dump

If all goes well you should have a db/data.yml file containing your data. Now we want to restore this data by a migration, so let’s create your second migration:

rails generate migration import_data

This second migration’s up method should be the following:


And you’re all set!

Take a deep breath and reset your existing database and run the migrations so it’s recreated. If by any chance something goes horribly wrong you still have the original database dump file stored somewhere safe, right?

rake db:reset
rake db:migrate

Tadaaa, your database should look just as it did before you reset it.

Now you can go ahead and create your models. Bonus tip: once you created your models, use the annotate gem to add the structure of the associated tables as handy comments at the beginning of your model files.

Reference: Creating a Rails Instance from an Existing MySQL DB.

Like what you read? Give Janos Rusiczki a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.