Categories
Rails

Renaming a model in Rails

When renaming a model in Rails (2.3), there are a range of files you may need to change:

Create a migration to rename the database table:

(rename_table :oldname, :newname)

Rename the model.
Edit any associations in other models.
Rename the controller (if required)
Modify routes.rb
Modify any links in views.
Rename views.
Rename the model in controllers and views.
Rename and modify any tests.

Moral of the story – name your models correctly from the start. Keep them as generic as possible. This post came about because I initially had a model for appointments for training sessions, so the model TrainingSession was created. Then I needed to store appointments which were for a different type of session, but I kept the model name the same, as it was only seen internally, and used a named scope. Now I need to store appointments of any type, so having code referring to TrainingSession will still work, but it makes it counterintuitive to refer to generic appointments as TrainingSession.generic. Instead, Appointment.generic and Appointment.training are so much more logical.

One reply on “Renaming a model in Rails”

Leave a Reply

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