Thursday, April 2, 2009

Migrations save your data headaches

One of the things I loved more than just about anything else about Rails was the way it handles databases. Specifically, changing the structure of databases as you make changes to your code.

Remember the other day when I said that running script/generate model would create a table in the database? Well, I lied, kind of. It doesn’t create the table itself, rather, it creates a migration file. The table isn’t actually created until you run the following command:

rake db:migrate
This checks the database to see what migrations have not yet been applied, then applies them in the order they were created.

Now, coming from Delphi, you might me more familiar with using tools like Database Desktop or MS-SQL’s Database Manager or even Microsoft Access. You use these tools to visually create your tables, and then access those tables using TQuerys (or other TDataSet classes)

What happens when you need to modify your database structure? Well, if you’re like me, you’ve probably written a whole lot of SQL scripts and you’ve written a database upgrade program that runs the SQL scripts and applies the changes.

Though if you’re like me, you’ve probably forgotten to do that sometimes, and ended up with a customer with data that doesn’t work because you didn’t add the fields you were supposed to.

Enter Rails migrations. These are created automatically whenever a model is generated, and you can generate new ones any time you want to in order to modify the database. This manages the complete history of the database structure for you, so that you don’t need to worry about it. You can always migrate your database back and forth as required.

No more missing SQL scripts. No more forgetting data changes. For the most part, it’s all handled for you!

Migrations are Ruby files, marked with a timestamp and a name, something like this:

The timestamp helps prevent any version number conflicts that might happen when you’ve got a bunch of people all working on the same project. It acts as the version number for the database.

No comments: