Ruby on Rails Add column with default value


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

Migrations with defaults might take a long time in large tables with for example PostgreSQL. This is because each row will have to be updated with the default value for the newly added column. To circumvent this (and reduce downtime during deployments), you can split your migration into three steps:

  1. Add a add_column-migration similar to the one above, but set no default
  2. Deploy and update the column in a rake task or on the console while your app is running. Make sure your application already writes data to that colum for new/updated rows.
  3. Add another change_column migration, which then changes the default of that column to the desired default value