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.
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.
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.
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
RailstoReact. 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.