Blankman
Blankman

Reputation: 267020

How to create a new not null column with existing data?

I am creating a new column in a table which is a uuid/guid.

add_column :users, :uuid, :string, null: false

I am setting the uuid using:

SecureRandom.uuid

The migration fails because the existing data doesn't have any value.

How can I set the value for each user with a new uuid during this migration?

Upvotes: 0

Views: 608

Answers (1)

Marcin Kołodziej
Marcin Kołodziej

Reputation: 5313

You have 2 options when adding a not null column:

  1. Provide a DB default
  2. Add a nullable column, update all the data, change the column to non nullable.

Depending on what DB you're using it might or might not allow you to set an expression as the default value.

Since you've mentioned you're using Postgres, you can read more here Rails syntax for providing the default will be

default: -> { 'uuid_generate_v1()' }

Upvotes: 2

Related Questions