简体   繁体   中英

Rails migration add a null: false column with an initial value that's not an ongoing default

I have this migration which I don't like:

    add_column :employers, :address_line_1, :string
    add_column :employers, :address_city, :string
    add_column :employers, :address_postcode, :string

    change_column_null :employers, :address_line_1, false, '123 default street'
    change_column_null :employers, :address_city, false, 'Default City'
    change_column_null :employers, :address_postcode, false, '123456'

Making the add_column lines have null: false is invalid since I have existing records, and I don't want any default value (except for at the time of this migration).

Can columns be added with an intial (but not default) value in a single line of code?

"Can columns be added with an intial (but not default) value in a single line of code?"

No. However, "change_column_null" can be used in a migration, and the fourth parameter actually sets a value for null columns without changing the "default" in the database.

https://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_column_null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM