How do you write a migration to rename an ActiveRecord model and its table in Rails?

前端 未结 5 1454
忘掉有多难
忘掉有多难 2020-11-29 14:56

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 cor

5条回答
  •  隐瞒了意图╮
    2020-11-29 15:40

    You also need to replace your indexes:

    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
    

    And rename your files etc, manually as other answers here describe.

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

    Make sure you can rollback and roll forward after you write this migration. It can get tricky if you get something wrong and get stuck with a migration that tries to effect something that no longer exists. Best trash the whole database and start again if you can't roll back. So be aware you might need to back something up.

    Also: check schema_db for any relevant column names in other tables defined by a has_ or belongs_to or something. You'll probably need to edit those too.

    And finally, doing this without a regression test suite would be nuts.

提交回复
热议问题