Scott's Recipes Logo

Rails Refactoring - From Enum to Model

Last Updated On: 2025-09-01 04:31:51 -0400

I’ve been in Rails for almost 20 years now. And last week was the first time I ever used an enum. And today was the day that I threw them all away.

My model was called Badge and my enum was called category. This made my new model BadgeCategory.

Here’s the process:

  1. Generate a new model using rails scaffold.
  2. Check the model for relationships and add in any custom addins / other code
  3. Edit the migration to make sure it is ok.
  4. Migrate the database.
  5. Copy the seeding routine from an old seeder to the new name structure.
  6. Edit the controller and add the needed security checks.
  7. Edit the seeding routine and make it right. This needs to have all the values of the old enum as well as any new values.
  8. Seed the data.
  9. Write a migration to add the new BadgeCategory to Badge.
  10. Write a data migration routine to map the existing categories to the new badge_category_id

Live Pro Tip: NEVER, EVER start your enum with 0. Primary keys don’t start with 0; they start with 1. By starting your enums with 0 you are guaranteeing that Step 9 is more complicated than necessary. If you start with 1 then you can simply copy the id values over instead of mapping them.

And here are the related commands:

rails g scaffold BadgeCategory name:string fid:string user:references
mate db/migrate/20250828094435_create_badge_categories.rb
bin/rails db:migrate
cp -p lib/tasks/domains.rake lib/tasks/badge_categories.rake
mate app/controllers/badge_categories_controller.rb
be rake badge_categories:init --trace
bin/rails g migration AddBadgeCategoryToBadges badge_category:references
bin/rails db:migrate
 be rake badge_categories:map_existing_categories_to_new_badge_category_id --trace