如何在项目中重命名 rails 控制器和模型 [英] How to rename rails controller and model in a project

查看:24
本文介绍了如何在项目中重命名 rails 控制器和模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想将 Corps 控制器更改为 Stores 和模型的相同(没有最终 s).

I wanted to change the Corps controller to Stores and the same (without final s) for the model.

在google上看,有人建议销毁然后重新生成控制器和模型.问题是它会擦除每个文件的实际代码!

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.

推荐答案

我会这样做:

创建迁移以更改表名(数据库级别).我假设您的旧表称为 corps.迁移内容将是:

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:

  • 文件重命名:corp.rb -> store.rb
  • store.rb的代码:将class Corp改为class Store
  • 重命名所有模型关联,如 has_many :corps -> has_many :stores
  • 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:

  • 文件重命名:corps_controller.rb -> stores_controller.rb
  • stores_controller.rb的代码:将class CorpsController改为class StoresController
  • File rename: corps_controller.rb -> stores_controller.rb
  • Code of stores_controller.rb: Change class CorpsController for class StoresController

重命名视图文件夹.从corpsstores.

Rename views folders. From corps to stores.

config/routes.rb 文件中的路径进行必要的更改,例如 resources :corps -> resources :stores,以及确保代码中的所有引用都从 corps 更改为 store (corps_path, ...)

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, ...)

记得运行迁移:)

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

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

 $ rake db:drop db:create db:migrate

这篇关于如何在项目中重命名 rails 控制器和模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆