Add a Postgres array column in Rails 3
February 3, 2018
While migrations in Rails 3 don’t have built-in support for Postgres array columns, its still possible to add an array column in a migration using SQL. Here’s how. First, generate a migration
bundle exec rails g migration AddEnabledFeaturesToAccounts
Modify the migration to something like
class AddEnabledFeaturesToAccounts < ActiveRecord::Migration
def up
execute <<-SQL
ALTER TABLE accounts ADD COLUMN enabled_features character varying(255)[] DEFAULT '{}';
SQL
end
end
The migration above adds a string array column. If you’d like to add an integer array column, change the SQL in the migration to add an integer array column
ALTER TABLE tickets ADD COLUMN cached_label_ids int[] DEFAULT '{}';
In case the table you’re adding the column to is huge, you may want to set the column default in a separate SQL statement to prevent the ADD COLUMN
statement from locking the table for minutes (or even hours)
class AddEnabledFeaturesToAccounts < ActiveRecord::Migration
def up
execute <<-SQL
ALTER TABLE accounts ADD COLUMN enabled_features character varying(255)[];
SQL
execute <<-SQL
ALTER TABLE accounts ALTER COLUMN enabled_features SET DEFAULT '{}';
SQL
end
end