您如何编写迁移以在 Rails 中重命名 ActiveRecord 模型及其表? [英] How do you write a migration to rename an ActiveRecord model and its table in Rails?

查看:18
本文介绍了您如何编写迁移以在 Rails 中重命名 ActiveRecord 模型及其表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在命名方面很糟糕,并意识到在我的 Rails 应用程序中有一组更好的模型名称.
有没有办法使用迁移来重命名模型及其对应的表?

I'm terrible at naming and realize that there are a better set of names for my models in my Rails app.
Is there any way to use a migration to rename a model and its corresponding table?

推荐答案

举个例子:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def self.up
    rename_table :old_table_name, :new_table_name
  end

  def self.down
    rename_table :new_table_name, :old_table_name
  end
end

我不得不手动重命名模型声明文件.

I had to go and rename the model declaration file manually.

在 Rails 3.1 和4、ActiveRecord::Migration::CommandRecorder 知道如何反向 rename_table 迁移,所以你可以这样做:

In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder knows how to reverse rename_table migrations, so you can do this:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    rename_table :old_table_name, :new_table_name
  end 
end

(您仍然需要手动重命名文件.)

(You still have to go through and manually rename your files.)

这篇关于您如何编写迁移以在 Rails 中重命名 ActiveRecord 模型及其表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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