Default Enum in Rails 6


Default Enum in Rails 6

Rails 6 provides a way to define default enum value. Let’s see how it works with an example. For this example we are using Rails alpha.

Default enum in action

Using the Post model, with status as draft & published, and will be using draft as default will be something like:

  class Post < ApplicationRecord
    enum status: %i[draft published], _default: :draft
  end


On checking a new post’s status turns out to be a draft. In previous versions of Rails this turns out to be nil.


default-enum-in-rails


Pull Request

Recommended Posts

Rails 5 adds OR Activerecord method
This or method was introduced in Rails 5, It returns a new ActiveRecord::Relation which is...
Descendants vs Subclasses in Ruby
Descendants has been a part of Rails ActiveSupport::DescendantsTracker for quite a while. However, Class#subsclasses is...
Ruby 3.1 adds subclasses method
Ruby 3.1 adds Class#subclasses method, which returns an array of subclasses directly inheriting from the...