你怎么写迁移到重命名一个ActiveRecord模型及其表Rails的?你怎么、重命名、模型、ActiveRecord

2023-09-08 15:47:54 作者:到此为止

我是可怕的,在命名和认识到,有一个更好的设置我的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 a way to use a migration to rename a model and its 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的::移民:: 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.)