Reversible migration for change_column_default from not having any default in Rails

前端 未结 7 2446
青春惊慌失措
青春惊慌失措 2021-02-18 21:34

The Rails guides to active record migrations says that you can do

change_column_default :products, :approved, from: true, to: false

I\'ve got a

7条回答
  •  萌比男神i
    2021-02-18 22:17

    Just to add a few points. If you are stuck with the Rails version not supporting reversible change_column_default, one option to get past the problem is:

    def change
        # If your dataset is small, just cache in memory, if large, consider file dump here:
        cache = Table.all
        # Full column def important for reversibility
        remove_column :table, :column, :type, { config_hash }
        # Re-add the column with new default:
        add_column  :table, :column, :type, { config_hash, default: 0 }
        # Now update the data with cached records (there might be more efficient ways, of course):
        cache.each do |rec|
            Table.find(rec.id).update(column: rec.column)
        end
    end
    

提交回复
热议问题