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'
end
end
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
end
end
This will drop whatever default was against status
and set it to nil
.
This article is a part of the "Rails migrations" series
- Rails Migrations for Beginners
- How to change the column type with Rails migrate
- Removing fields with a Rails migration
- Running Rails migrations automatically on Heroku
- How to comment Rails migrations
- Create or remove columns or tables with Rails migrations
- This Article
- What are the square brackets in my Rails migrations?
- What are Rails Migrations
- Forcing a Rails database column to be not null
- Irreversible Rails Migrations