Ruby-on-rails 如何在项目中重命名 rails 控制器和模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11924124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:51:02  来源:igfitidea点击:

How to rename rails controller and model in a project

ruby-on-railsmodelcontrollerrename

提问by htaidirt

I started a Rails app and everything works fine. But now, I would like to rename a controller and the associated model:

我启动了一个 Rails 应用程序,一切正常。但是现在,我想重命名控制器和相关模型:

I wanted to change the Corpscontroller to Storesand the same (without final s) for the model.

我想将Corps控制器更改为Stores和模型相同(没有 final 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? Thanks in advance.

有什么解决办法吗?提前致谢。

回答by Nobita

Here is what I would do:

这是我会做的:

Create a migrationto change the table name (database level). I assume your old table is called corps. The migration content will be:

创建迁移以更改表名(数据库级别)。我假设你的旧桌子叫做corps。迁移内容将是:

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 Corpfor class Store
  • Rename all the model associations like has_many :corps-> has_many :stores
  • 文件重命名:corp.rb->store.rb
  • 代码store.rb:更改class Corpclass Store
  • 重命名所有模型关联,如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 CorpsControllerfor class StoresController
  • 文件重命名:corps_controller.rb->stores_controller.rb
  • 代码stores_controller.rb:更改class CorpsControllerclass StoresController

Rename views folders. From corpsto stores.

重命名视图文件夹。从corpsstores

Make the necessary changes in paths in the config/routes.rbfile, 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 :corps-> resources :stores,并确保代码中的所有引用都从 corps 更改为 store (corps_path, ...)

Remember to run the migration :)

记得运行迁移:)

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

如果以前的不可行,请尝试删除 db/schema.rb 并执行:

 $ rake db:drop db:create db:migrate

回答by Holly

In addition to Nobita answer you similarly need to change the test& helperclass definitions & file names for corpsto store. More Importantlyyou should change corpsto storein your config/routes.rbfile

除了大雄回答你同样需要改变测试辅助类的定义和文件名称为corpsstore更重要的是,您应该在config/routes.rb文件中更改corpsstore

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& generateis a better option. I've given an answer how to do this here: Rails : renaming a controlller and corresponding model

我认为你所看到的destroy&generate是一个更好的选择。我在这里给出了如何做到这一点的答案:Rails : renaming a controller and相应模型

回答by Asme Just

You can try the Rails Refactorgem too, a Command line tool for simple refactors like rename model and controller for Rails projects

您也可以尝试Rails Refactorgem,这是一个用于简单重构的命令行工具,例如 Rails 项目的重命名模型和控制器

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

...

rails 项目的基本重命名和重构。尽管这些并不完美,但它们会为您完成很多工作并节省您的时间。

在使用之前,建议您从一个干净的存储库状态开始,以便您可以轻松查看更改。

安装:
gem install rails_refactor

在使用之前,请确保您cd 到您的 rails 项目的根目录。

要重命名控制器:
rails_refactor rename OldController NewController

  • 重命名文件中的控制器文件和类名
  • 重命名控制器规范文件和文件中的类名
  • 重命名视图目录
  • 重命名文件中的帮助文件和模块名称
  • 更新路线

要重命名控制器操作:
$ rails_refactor rename DummyController.old_action new_action

  • 重命名控制器类文件中的控制器动作
  • 重命名所有格式的视图文件

要重命名模型:
$ rails_refactor rename OldModel NewModel

  • 重命名文件中的模型文件和类名
  • 重命名文件中的规范文件和类名
  • 重命名文件中的迁移、类名和表名

...

回答by Dan

I addition to Nobita's answer (which I would comment on if I had enough rep), if you're feeling brave then the changes to filenames and references to the model in your code can be automated somewhat. For instance, to change references in your code you can use

除了 Nobita 的回答(如果我有足够的代表,我会评论),如果您感到勇敢,那么对代码中的文件名和模型引用的更改可以在某种程度上自动化。例如,要更改代码中的引用,您可以使用

Singular, minus and mayus:

单数,减号和mayus:

grep -rl corp | xargs sed -i 's/corp/store/g'
grep -rl Corp | xargs sed -i 's/Corp/Store/g'

Plural, minus and mayus (singular replace the plural if plural only needs and s character at the end):

复数、减号和 mayus(如果复数只需要在末尾加上 s 字符,则单数替换复数):

grep -rl corps | xargs sed -i 's/corps/stores/g'
grep -rl Corps | xargs sed -i 's/Corps/Stores/g'

Rename files:

重命名文件:

find . -name '*corp*' -exec bash -c 'mv 
shopt -s globstar
rename -v corps stores app/**/*corps* config/**/*corps* test/**/*corps*
${0/corp/store}' {} \;


And there is a utility called rename on some *nix flavours (including Slackware) which will help you rename the files:

在某些 *nix 版本(包括 Slackware)上有一个名为 rename 的实用程序,可以帮助您重命名文件:

shopt -s globstar
rename -v 's/corps/stores/' app/**/*corps* config/**/*corps* test/**/*corps*

Check rename is what you think it is though, I've known other distributions like Ubuntu to ship with a different utility of the same name (see https://unix.stackexchange.com/questions/78621/find-rename-command-doesnt-work). On Ubuntu you would do this instead:

检查重命名是你认为的那样,我知道像 Ubuntu 这样的其他发行版带有同名的不同实用程序(参见https://unix.stackexchange.com/questions/78621/find-rename-command-不工作)。在 Ubuntu 上,你会这样做:

rename_column :table, :old_id, :new_id

Note that you want to avoid renaming any files in db/ except possibly in your seeds.rb file, so you probably want to exclude this directory and make any changes manually.

请注意,您希望避免重命名 db/ 中的任何文件,除非可能在您的 seed.rb 文件中,因此您可能希望排除此目录并手动进行任何更改。

回答by Pwnrar

One other important thing is that you need to update the model associations, which you'll have to do whether you rename manually or destroy and generate the resource (since they exist in the other models). You can either run a migration to change the column names of the foreign keys in the database and change all references to those foreign keys in the code:

另一件重要的事情是您需要更新模型关联,无论您是手动重命名还是销毁并生成资源(因为它们存在于其他模型中),您都必须这样做。您可以运行迁移以更改数据库中外键的列名,并更改代码中对这些外键的所有引用:

belongs_to :new, foreign_key: "old_id"

or set a custom foreign key when declaring the association that uses the old foreign key:

或在声明使用旧外键的关联时设置自定义外键:

##代码##

Also if your resource includes images, they are often stored in a directory that includes the resource name but (with carrierwave at least) once the resource's name is changed they'll be referenced incorrectly (file exists at '/uploads/old/image/1/pic.jpg' but is looked for at 'uploads/new/...'), so you'll have to either delete and re-upload the images, move them to the new path, or perhaps change where they're being looked for.

此外,如果您的资源包含图像,它们通常存储在包含资源名称的目录中,但是(至少使用carrierwave)一旦资源名称更改,它们将被错误地引用(文件存在于'/uploads/old/image/ 1/pic.jpg' 但在 'uploads/new/...' 中查找),因此您必须删除并重新上传图像,将它们移动到新路径,或者可能更改它们的位置'正在寻找。

回答by Benjamin J. Benoudis

And if you have model tests, you need to change:

如果您有模型测试,则需要更改:

File rename: corp_test.rb -> store_test.rb (also for controller tests, integration tests, fixture, etc.)

文件重命名:corp_test.rb -> store_test.rb(也用于控制器测试、集成测试、夹具等)

Code of store_test.rb: Change class CorpTest for class StoreTest.

store_test.rb 的代码:将类 CorpTest 更改为类 StoreTest。

And all the references of corp in the controller, model, integration, fixture tests.

以及 corp 在控制器、模型、集成、夹具测试中的所有引用。

回答by ChaosPredictor

As someone that just finish this painful process the MOST important step is to build enough TESTSto check as much functionality as possible. They should cover not only the model/controller that you plan to rename but also all other models/controllers/views parts. Anyhow it's a good (or maybe even a must) practice.

正如有人说只是完成这个痛苦的过程中最重要的一步是建立足够的试验,以检查尽可能多的功能成为可能。它们不仅应涵盖您计划重命名的模型/控制器,还应涵盖所有其他模型/控制器/视图部件。无论如何,这是一个很好的(甚至可能是必须的)练习。

Do this steps by iterations, sometimes you need to comeback to steps few times (5 and more) to discover additional files that need to be changed. And now for the rename steps:

通过迭代执行此步骤,有时您需要返回步骤几次(5 次或更多)以发现需要更改的其他文件。现在是重命名步骤:

  1. Change all the files (name and content) the include Corps/Corpto Stores/Storein db/migratefolder
  2. Try to run:

    rake db:drop:all

    rake db:create

    rake db:migrate

  3. Change content of db/seeds.rbfile.

  4. Try to run: rake db:seed --trace(In this step you may need to change some other model/controller files.)
  5. Change test/fixturesfiles. you may need to change not only corps.yml but other related files (some files may include corp_id).
  6. Try to run your tests, it's better to run it with fixed seed (add: TESTOPTS="--seed=1981"or any other number)
  7. Rename to files (name and content) be carefull sometimes you need to change test and other app file
  1. 更改的所有文件(名称和内容)将包括Corps/CorpStores/Storedb/migrate文件夹中
  2. 尝试运行:

    耙 db:drop:all

    耙数据库:创建

    耙数据库:迁移

  3. 更改db/seeds.rb文件内容。

  4. 尝试运行:( rake db:seed --trace在这一步中,您可能需要更改一些其他模型/控制器文件。)
  5. 更改test/fixtures文件。您可能不仅需要更改 corps.yml,还需要更改其他相关文件(某些文件可能包含 corp_id)。
  6. 尝试运行您的测试,最好使用固定种子(添加:TESTOPTS="--seed=1981"或任何其他数字)运行它
  7. 重命名文件(名称和内容)要小心,有时您需要更改测试和其他应用程序文件

回答by Ravi

for controller you will have to make change in following places if you're doing it manually:

对于控制器,如果您手动进行更改,则必须在以下位置进行更改:

  • route
  • app/views
  • app/controllers
  • test/controllers
  • app/helper
  • app/assets/javascripts/
  • app/assets/stylesheets/
  • 路线
  • 应用程序/视图
  • 应用程序/控制器
  • 测试/控制器
  • 应用程序/助手
  • 应用程序/资产/javascripts/
  • 应用程序/资产/样式表/

for model, Nobita's answer is pretty good

对于模型,大雄的回答非常好