rails - apply default value for enum field
You can set the default value from the database declaration.
create_table :templates do |t|
t.column :status, :integer, default: 0
end
And then, map the relationship as following
class Template < ActiveRecord::Base
enum status: { draft: 0, published: 1 }
end
Rails 6.1+
Starting from Rails 6.1, it is possible to set a default enum value right in the model. For example:
class Template < ActiveRecord::Base
enum status: [:draft, :published], _default: :draft
end
Here is a link to relative PR and a link to the docs.
Rails 7+
Starting from Rails 7, there is no more need to use leading underscore. For example:
class Template < ActiveRecord::Base
enum :status, [:draft, :published], default: :draft
end
Here is a link to relative PR and a link to the docs.