首页 文章

如何编写迁移以在Rails中重命名ActiveRecord模型及其表?

提问于
浏览
386

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

4 回答

  • 44

    这是一个例子:

    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
    

    我必须手动重命名模型声明文件 .

    Edit:

    在Rails 3.1和4中, ActiveRecord::Migration::CommandRecorder 知道如何反转rename_table迁移,因此您可以这样做:

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

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

  • 61

    在Rails 4中,我所要做的只是改变

    def change
      rename_table :old_table_name, :new_table_name
    end
    

    我的所有索引都是为我照顾的 . 我不需要通过删除旧索引并添加新索引来手动更新索引 .

    并且它也可以根据索引使用上升或下降的变化 .

  • 554

    其他答案和评论涉及表重命名,文件重命名和通过代码进行grepping .

    我想补充几点:

    让我们使用我今天面对的一个现实世界的例子:将模型从“商家”重命名为“商业” .

    • Don 't forget to change the names of dependent tables and models in the same migration. I changed my Merchant and MerchantStat models to Business and BusinessStat at the same time. Otherwise I' d在执行搜索和替换时不得不做太多挑选和选择 .

    • 对于通过外键依赖于您的模型的任何其他模型,其他表' foreign-key column names will be derived from your original model name. So you'll也希望对这些依赖模型执行一些rename_column调用 . 例如,我必须在各种连接表(对于has_and_belongs_to_many关系)和其他从属表(对于正常的has_one和has_many关系)中将'merchant_id'列重命名为'business_id' . 否则我会以'business_stat.merchant_id'指向'business.id'的列结束 . Here's a good answer about doing column renames.

    • 在grepping时,请记住搜索字符串的单数,复数,大写,小写甚至大写(可能出现在注释中)版本 .

    • 它's best to search for plural versions first, then singular. That way if you have an irregular plural - such as in my merchants :: businesses example - you can get all the irregular plurals correct. Otherwise you may end up with, for example, ' businesss ' (3 s' s)作为一个中间状态,导致更多的搜索和替换 .


  • 23

    您还需要替换索引:

    class RenameOldTableToNewTable< ActiveRecord:Migration
      def self.up
        remove_index :old_table_name, :column_name
        rename_table :old_table_name, :new_table_name
        add_index :new_table_name, :column_name
      end 
    
      def self.down
        remove_index :new_table_name, :column_name
        rename_table :new_table_name, :old_table_name
        add_index :old_table_name, :column_name
      end
    end
    

    并按照此处描述的其他答案手动重命名您的文件等 .

    见:http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

    编写此迁移后,请确保您可以回滚并前滚 . 如果出现问题并且试图影响不再存在的事物的迁移,它会变得棘手 . 最好将整个数据库丢弃,如果无法回滚,请重新开始 . 所以要注意你可能需要备份一些东西 .

    另外:检查schema_db以查找has_或belongs_to或其他东西定义的其他表中的任何相关列名 . 你可能也需要编辑它们 .

    最后,没有回归测试套件这样做会很疯狂 .

相关问题