Rails migrations - add default value to existing column

Here's how to update an existing column to use a default value

If we don’t supply a default value to a column Rails will default it to be nil. A lot of the time this is fine, say a user hasn’t supplied a optional attribute then it doesn’t really matter whether it’s set or not but say we have an Article model and we want to set a enumerable status against it, say draft or published, it would be good to have a default. Generally in this case if an admin were creating a new article we would want the status to be draft so it isn’t visible in a half finished state. When we’re first creating our system sometimes these requirements only present themselves over time and we have to go back to update them. So let’s update our articles to default to a status of draft using change_column_default.

How to update the default value from a column using a Rails migration?

First of all run a migration like rails generate migration UpdateStatusDefaultToDraftArticles. Then update the migration to have this:

class UpdateStatusDefaultToDraftArticles < ActiveRecord::Migration[6.1]
  def change
    change_column_default :articles, :status, from: nil, to: 'draft'

This updates the columns default value from nil to 'draft' meaning any new articles creating will have a default status of 'draft'. Using from: and to: is best as it’s more explanatory and allows the migration to be reversed if your requirements change but you could write change_column_default :articles, :status, 'draft' instead.

How to drop the default value from a column using a Rails migration?

If you wanted to drop the default value you can run:

class UpdateDefaultOnStatusArticles < ActiveRecord::Migration[6.1]
  def change
    change_column_default :articles, :status, nil

This will drop whatever default was against status and set it to nil.

Recent posts View all

Web Dev

Render's Support

I'm really happy with Render's support and will be recommending them for people to consider

Web dev

Free tools to improve your website

There are lots of freely available tools to help get a sense check on how your website is doing and recommend improvements