The problem with renaming a model in Rails

So you’ve decided to rename a model in Rails. What could be simpler than renaming and editing a bunch of files? You make your edits in development, run migrations and so on.
There’s a potential issue you might hit though. Suppose you have model Foo, which you want to modify (e.g. add a column). So you create a migration with:
add_column :foo, :quantity, :integer
…and you run your migration.
Then you decide you want to rename the model to Bar. So you use rename_table in your migration, and rename and edit the appropriate files. All works beautifully.
Now you come to deploy, and it all goes wrong when you migrate the database, saying it can’t find the model. The reason? Well your first migration now refers to a model that doesn’t exist, because the new model file is in place.
The messy solution is to perform the migration yourself, by renaming the database table directly in the database.
The clean solution is to avoid making changes like this in the first place. I guess it’s an example of where “deploy often” can reap benefits.

This entry was posted in Rails. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *