Add column with default value
suggest changeThe following example adds a column admin to the users table, and gives that column the default value false.
class AddDetailsToUsers < ActiveRecord::Migration[5.0]
def change
add_column :users, :admin, :boolean, default: false
end
end
On PostgreSQL before version 11, adding a column with a default can take a long time on a large table, because each existing row is rewritten with that default. To avoid that rewrite (and reduce downtime during deployment), split the change into three steps:
- Add an
add_columnmigration like the one above, but with no default. - Deploy, and backfill the column in a Rake task or the console while the app is running. The app must already write the column for new and updated rows.
- Add a
change_column_defaultmigration that sets the column default to the desired value. That changes the default for future inserts only; it does not rewrite existing rows.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents