Rails – dump an existing database schema so it can be rebuilt easily

One of my gripes (or possibly misunderstandings) with Rails is that you have to make the schema within Rails. I find that difficult – I want to plan it externally, create the schema, and then use it in my app. Perhaps there is an easier way to accomplish that, but here’s what I do.

  1. I create my schema and do my planning in MySQL workbench. I can build the ER diagrams and visualize what it is I’m doing.
  2. I export the schema to SQL and then use it to create my new database.
  3. I point my application to the new database.
  4. Then I run `rake db:schema:dump` which reads the database and create the db/schema.db file. This file represents the whole database and can be used to recreate it from scratch.
  5. Then last for good measure, I make sure my model files are annotated so I can easily reference the columns as I’m working with the command `bundle exec annotate –position before`. Note that you need to be using the gem ‘annotate’ in your Gemfile for that command to work.
  6. Any time I make a change to my schema, I run `rake db:schema:dump` and `bundle exec annotate –position before` again to update the application.

Now, say you want to install your application on another machine with a different database. Move your application code over, create a blank database and point your database.yml to it. Then run the command `rake db:schema:load` to recreate the schema. Done!

If anyone knows of an easier way to do external modeling and schema creation while making it easy to install your application ‘the Rails way’ on other machines, please do leave a comment!

Leave a Reply

Your email address will not be published.