Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...