How to rename rails controller and model in a project
Here is what I would do:
Create a migration to change the table name (database level). I assume your old table is called corps. The migration content will be:
class RenameCorpsToStores < ActiveRecord::Migration def change rename_table :corps, :stores endend
Change your model file name, your model class definition and the model associations:
- File rename:
corp.rb
->store.rb
- Code of
store.rb
: Changeclass Corp
forclass Store
- Rename all the model associations like
has_many :corps
->has_many :stores
Change your controller file name and your controller class definition:
- File rename:
corps_controller.rb
->stores_controller.rb
- Code of
stores_controller.rb
: Changeclass CorpsController
forclass StoresController
Rename views folders. From corps
to stores
.
Make the necessary changes in paths in the config/routes.rb
file, like resources :corps
-> resources :stores
, and make sure all the references in the code change from corps to stores (corps_path, ...)
Remember to run the migration :)
If previous is not possible, try to delete the db/schema.rb and execute:
$ rake db:drop db:create db:migrate
In addition to Nobita answer you similarly need to change the test & helper class definitions & file names for corps
to store
. More Importantly you should change corps
to store
in your config/routes.rb file
So in total you're making changes to the Controller, associated Model, Views, Helpers, Tests and Routes files.
I think what you’ve seen suggested with destroy
& generate
is a better option. I’ve given an answer how to do this here: Rails : renaming a controlller and corresponding model
You can try the Rails Refactor gem too, a Command line tool for simple refactors like rename model and controller for Rails projects
Usage:
Basic renames and refactorings for rails projects. Although these are not perfect, they'll do a lot of the work for you and save you time.
Before using, recommend that you start from a clean repository state so you can easily review changes.
To install:
gem install rails_refactor
Before use, make sure you cd to the root of your rails project.
To rename a controller:
rails_refactor rename OldController NewController
- renames controller file & class name in file
- renames controller spec file & class name in file
- renames view directory
- renames helper file & module name in file
- updates routes
To rename a controller action:
$ rails_refactor rename DummyController.old_action new_action
- renames controller action in controller class file
- renames view files for all formats
To rename a model:
$ rails_refactor rename OldModel NewModel
- renames model file & class name in file
- renames spec file & class name in file
- renames migration & class name & table names in file
...