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

前端 未结 5 1470
忘掉有多难
忘掉有多难 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:27

    Here's an example:

    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.

    Edit:

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

提交回复
热议问题