BigBinary Blog

We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.

Rails 6.1 allows configuring default value of enum attributes

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.

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

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

1class AddColumnStatusToPosts < ActiveRecord::Migration[6.0]
2  def change
3    add_column :posts, :status, :integer, default: 0
4    add_column :posts, :category, :string, default: "Rails"
5  end
6end

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

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

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 for more details on this.

Abhay Nikam in Rails 6.1
July 21, 2020
Share

Subscribe to our newsletter