008 RC ActiveRecord Migration Gotchas




Rails Coach show

Summary: Rails Migrations are generally pretty straightforward, but there are a few things that people do that wind up giving them headaches later on. First, don't change migrations once they've been committed or deployed. This causes problems because ActiveRecord tracks migrations that have already been run. So, editing a migration that's already been run will result in your changes not being made. Second, use Rails' built in migration and model generators. It generates the id number in the front of the migration from a timestamp which minimizes that possibility of having a collision on the migration's identifier. Third, create mapping tables in your migrations so your connections work. When you do these migrations, make sure you have ":id => false" on your "create_table" call. When creating mapping tables, eliminate the meta data on the mapping unless you're using a "has_many :through =>" relationship. Adding meta fields to mapping tables will be deprecated in Rails 3.1. Fourth, add indexes to all foreign id's. Those are the "_id" columns in your tables. I've used the rails_indexes plugin for this. Fifth, don't reference Models in your migrations. If your Model implementation or attribute sets change, your migrations may no longer work. Instead, call "execute" with your SQL queries to update and save data in the database in your migrations. Finally, go check out the Ruby Rogues podcast! You can also get my interview with Tom Preston-Werner from Github here.