We can add a PostgreSQL array column with a default empty array using:
add column things integer[] not null default '{}';
Today I added an array of integers to a PostgreSQL table, and like all such
migrations, it will default to null for each new record.
This was a problem, because I wanted to use Rails built-in PostgreSQL array
support to make decisions based on that data. Ruby array methods like include?
will raise NoMethodError: undefined method 'include?' for nil:NilClass if that
array is ever null / nil, which it is by default.
This led me to learn how to set the default value to an empty array using
PostgreSQL array literal syntax. I was then able to include a not null
constraint as an added benefit:
alter table posts
add column slack_notified integer[] not null default '{}';