---
title: "Rails 6.1 allows configuring default value of enum attributes"
description: "Rails 6.1 allows enums attributes to configure the default value"
canonical_url: "https://www.bigbinary.com/blog/rails-6-1-allows-enums-attributes-to-have-default-value"
markdown_url: "https://www.bigbinary.com/blog/rails-6-1-allows-enums-attributes-to-have-default-value.md"
---

# Rails 6.1 allows configuring default value of enum attributes

Rails 6.1 allows enums attributes to configure the default value

- Author: Abhay Nikam
- Published: July 21, 2020
- Categories: Rails 6.1, Rails

Rails 6.1 makes it easier to configure a default value for Active Record enum
attributes.

Let's take an example of blog posts with status and category columns.

```ruby
class Post < ApplicationRecord
  enum status: %i[draft reviewed published]
  enum category: { rails: "Rails", react: "React" }
end
```

Before Rails 6.1, defaults for enum attributes can be configured by applying
`default` on the database level.

```ruby
class AddColumnStatusToPosts < ActiveRecord::Migration[6.0]
  def change
    add_column :posts, :status, :integer, default: 0
    add_column :posts, :category, :string, default: "Rails"
  end
end
```

After Rails 6.1, defaults for enum attributes can be configured directly in the
Post model using `_default` option.

```ruby
class Post < ApplicationRecord
  enum status: %i[draft reviewed published], _default: "draft"
  enum category: { rails: "Rails", react: "React" }, _default: "Rails"
end
```

The new approach to set enum defaults has following advantages. Let's understand
keeping the context of Post model with category as an example.

- When the category default value changes from `Rails` to `React`. We have to
  add a new migration in Rails 6 and previous versions to update the database
  column default.
- Let say the default value for post category(i.e: `Rails`) is removed from the
  enum from Post model. Rails 6 and previous versions wouldn't throw an
  exception and continue to work without setting any default value. Rails 6.1
  with new syntax would raise an exception.

Check out the [pull request](https://github.com/rails/rails/pull/39820) for more
details on this.

## Links

- [Human page](https://www.bigbinary.com/blog/rails-6-1-allows-enums-attributes-to-have-default-value)
