Rails migration for change column

后端 未结 9 1070
一个人的身影
一个人的身影 2020-11-28 17:24

We have script/generate migration add_fieldname_to_tablename fieldname:datatype syntax for adding new columns to a model.

On the same line, do we have a

9条回答
  •  再見小時候
    2020-11-28 18:12

    I'm not aware if you can create a migration from the command line to do all this, but you can create a new migration, then edit the migration to perform this taks.

    If tablename is the name of your table, fieldname is the name of your field and you want to change from a datetime to date, you can write a migration to do this.

    You can create a new migration with:

    rails g migration change_data_type_for_fieldname
    

    Then edit the migration to use change_table:

    class ChangeDataTypeForFieldname < ActiveRecord::Migration
      def self.up
        change_table :tablename do |t|
          t.change :fieldname, :date
        end
      end
      def self.down
        change_table :tablename do |t|
          t.change :fieldname, :datetime
        end
      end
    end
    

    Then run the migration:

    rake db:migrate
    

提交回复
热议问题