I started a Rails app and everything works fine. But now, I would like to rename a controller and the associated model:
I wanted to change the Corps controller to Stores and the same (without final s) for the model.
Looking on google, people suggested to destroy and then generate again the controller and model. The problem is that it will erase the actual code of each files!
What’s the solution?
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:
Change your model file name, your model class definition and the model associations:
corp.rb->store.rbstore.rb: Changeclass Corpforclass Storehas_many :corps->has_many :storesChange your controller file name and your controller class definition:
corps_controller.rb->stores_controller.rbstores_controller.rb: Changeclass CorpsControllerforclass StoresControllerRename views folders. From
corpstostores.Make the necessary changes in paths in the
config/routes.rbfile, likeresources :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: