attilagyorffy.com

Avoiding PG::NotNullViolation errors when adding new columns in Rails migrations

Introduction

Attila Györffy

Attila Györffy

I'm a Ruby/JS dev/trainer with a focus on quality. An ex-Londoner, @terracycle, @ubxd, @lastfm. Follow me at http://twitter.com/attilagyorffy


PostgreSQL rubyonrails ActiveRecord

Avoiding PG::NotNullViolation errors when adding new columns in Rails migrations

Posted by Attila Györffy on .
Featured

PostgreSQL rubyonrails ActiveRecord

Avoiding PG::NotNullViolation errors when adding new columns in Rails migrations

Posted by Attila Györffy on .

I have seen this being a common question across newcomers to Rails. When you are adding a new column to an existing table with a non-null constraint, you start writing a migration as follows:

This will raise a PG::NotNullViolation error as postgres is smart enough to know that there are existing rows in your table and won't allow the migration to cause these to become invalid. (It has no idea what should be the value of the new columns in the existing rows.)

Fear not, you can overcome this issue by first adding the column, updating existing records with some default value and then adding the null constraint to your column. You can do it all in a single migration.

For example adding first and last names to Devise users could be as simple as follows:

Attila Györffy

Attila Györffy

https://attilagyorffy.com

I'm a Ruby/JS dev/trainer with a focus on quality. An ex-Londoner, @terracycle, @ubxd, @lastfm. Follow me at http://twitter.com/attilagyorffy

View Comments...