コントローラー名とモデル名の変更手順-Ruby on rails-

Hi:) When it’t time to blog, I translate and learn.
ということで今日もStack over flowの記事から抜粋。
記事表題は「How to rename rails controller and model in a project
(railsのプロジェクトでとうやったらコントローラ名とモデル名を変更するのか)」
です。
それでは記事を翻訳してみよう。

質問

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.

CorpsコントローラーをStoresコントローラーに変えたく、モデルも(語尾のsを省いて)同様に名前を変えたいんだ。

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?

何か解決策はあるかな?

回答

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:

テーブル名(データベースも)を変更する為にmigrationを作る。君の古いテーブル名はcorpsだろう。
migrationの中身はこうであろう。

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  
  
# ファイル名変更:corp.rb -> store.rb  
  
Code of store.rb: Change class Corp for class Store  
  
# store.rb内のclass Corpをclass Storeに  
  
Rename all the model associations like has_many :corps -> has_many :stores  
  
# モデルに関連したものを全て変更。例えばhas_many:corps -> has_many:stores

Change your controller file name and your controller class definition:

コントローラーのファイル名とクラス名を変更しよう。

File rename: corps_controller.rb -> stores_controller.rb  
  
# ファイル名変更 : corps_controller.rb -> stores_controller.rb  
  
Code of stores_controller.rb: Change class CorpsController for class StoresController  
  
# stores_controller.rb内のclass CorpsControllerをclass StoresControllerに  
  
Rename views folders. From corps to stores.  
  
# ビューのフォルダ名もcorpsから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, …)

config/routes.rb内の必要なパス名を変更する。例えばresources :corpsresources :storesに。
corpsをstoresに変えたか注意深く確認しよう。(corps_path,…)

Remember to run the migration :)

migrationを実行するのを忘れないでね:)

If previous is not possible, try to delete the db/schema.rb and execute:

もし上記のやり方で上手く行かなかったら、db/schema.rbを削除して次を実行しよう。

 $rake db:drop && rake db:create && rake db:migrate

終    

かなり無難なやり方って感じw
でもこの回答に118のいいねが付いているので結構な賛同を得ているやり方のようだ。
私も実際にこれやってみて、vim:%s/corps/stores/gみたいにやればあっさりcontroller名とmodel名を変えることができた。

See you!!

リンク How to rename rails controller and model in a project - Stack Overflow