Add a default value to a column through a migration

后端 未结 7 1678
旧巷少年郎
旧巷少年郎 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:30

    Using def change means you should write migrations that are reversible. And change_column is not reversible. You can go up but you cannot go down, since change_column is irreversible.

    Instead, though it may be a couple extra lines, you should use def up and def down

    So if you have a column with no default value, then you should do this to add a default value.

    def up
      change_column :users, :admin, :boolean, default: false
    end
    
    def down
      change_column :users, :admin, :boolean, default: nil
    end
    

    Or if you want to change the default value for an existing column.

    def up
      change_column :users, :admin, :boolean, default: false
    end
    
    def down
      change_column :users, :admin, :boolean, default: true
    end
    

提交回复
热议问题