Add column with default value

suggest change

The 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:

  1. Add an add_column migration like the one above, but with no default.
  2. 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.
  3. Add a change_column_default migration that sets the column default to the desired value. That changes the default for future inserts only; it does not rewrite existing rows.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents