Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename rails controller and model in a project

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!

Any solution? Thanks in advance.

like image 971
htaidirt Avatar asked Aug 12 '12 17:08

htaidirt


People also ask

What decides which controller receives which requests in Rails?

I fetched this definition from the official rails guide: A controller's purpose is to receive specific requests for the application. Routing decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different actions.


2 Answers

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   end end 

Change your model file name, your model class definition and the model associations:

  • File rename: corp.rb -> store.rb
  • Code of store.rb: Change class Corp for class 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: Change class CorpsController for class 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 
like image 121
Nobita Avatar answered Sep 22 '22 16:09

Nobita


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

like image 41
Holly Avatar answered Sep 19 '22 16:09

Holly