A migration is simply a Ruby source file in your application’s db/migrate directory. These files help to make small changes to the database extremely easy and quick. Want to add a table or rename a column? Write another migration and run rake db:migrate. With automatic versioning you are able to see the changes made to the model just by looking at the latest migration file. No more repetitive SQL queries. Now you can access your data in an understandable way right in your code. With that, let’s get coding!
First we can use either the rails generator to create a migration or use the model generator, which will also give us a migration file. Note: you could create these files by hand, but it is less error-prone and probably more efficient to use a built-in generator.
To create a migration with the model generator we would do something like this:
ruby script/generate model post
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/post.rb
create test/unit/post_test.rb
create test/fixtures/posts.yml
create db/migrate
create db/migrate/20090113055719_create_posts.rb
To create a migration on its own we would do something similar to this:
ruby script/generate migration add_category_column
exists db/migrate
create db/migrate/20090113055952_add_category_column.rb
To run the migration we use the db:migrate task
When running the db:migrate Rake task, a schema_migrations table is looked for to keep track of migration versions. If one isn’t found it will be created on the fly. After each migration is run a row in the schema_migration table is added.
You can also use the db:migrate Rake task to force the database to a specific version by supplying it with the Version= parameter.
rake db:migrate VERSION=20090113055719
To revert the database to it’s original state supply Version= paramter with 0.
rake db:migrate VERSION=0
If you run a migration whose version is higher than the version of the current database, the migration will be applied. Somewhat differently, if you run a migration whose version is lower than the version of the current database, Rails will look for the migration file whose number matches the database version and undo it.
I hope this tutorial has helped you to begin to understand ActiveRecord and how useful migrations can be. In the next article in this series we look at what makes up a migration in more detail.