Add a default value to a column through a migration

后端 未结 7 1676
旧巷少年郎
旧巷少年郎 2020-11-28 02:16

How do I add a default value to a column that already exists through a migration?

All the documentation I can find shows you how to do it if the column doesn\'t alr

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 02:23

    Execute:

    rails generate migration add_column_to_table column:boolean
    

    It will generate this migration:

    class AddColumnToTable < ActiveRecord::Migration
      def change
        add_column :table, :column, :boolean
      end
    end
    

    Set the default value adding :default => 1

    add_column :table, :column, :boolean, :default => 1

    Run:

    rake db:migrate

提交回复
热议问题