JT Book a call

Blog

Enum validation in Ruby on Rails 7.1

Published

2 min read

Enum validation in Ruby on Rails 7.1

Ruby enum with validate true, where assigning an invalid status makes valid? return false

The latest version of Rails 7.1 introduces the ability to validate enums, enhancing data integrity and error handling in Rails models. Enums in Rails allow defining a set of permissible values for an attribute. Prior to Rails 7.1, assigning an invalid enum value would raise an ArgumentError, necessitating manual validation checks. The updated feature in Rails 7.1 streamlines this process by enabling built-in enum validation options within ActiveRecord objects.

Before Rails 7.1 #

    class Project < ApplicationRecord
      enum status: [:active, :inactive, :archived] 
    end
    
    project = Project.find_by(name: "JT Project")
    
    project.status = :new
    => `assert_valid_value': 'new' is not a valid status (ArgumentError)

To avoid ArgumentError exception programmers used this trick:

    project = Project.find_by(name: "JT Project")
    status_value = :new
    
    if Project.statuses[status_value].present?
      project.status = status_value
    else
      # raise more consistent error than ArgumentError
    end

After Rails 7.1 #

    class Project < ApplicationRecord
      enum status: [:active, :inactive, :draft], validate: true 
    end
    
    project = Project.find_by(name: "JT Project")
    
    project.status = :new # Now in this place we do not receive the error ArgumentError
    project.valid?
    => false

Pay attention on validate: true in enum declaration.

We also can send additional rules to validation. For example: validate: { allow_nil: true }

By leveraging the new enum validation feature in Rails 7.1, developers can ensure the integrity of enum attributes, streamline validation processes, and enhance the overall robustness of Rails applications.

Paul Keen is an Open-Source Contributor and a Chief Technology Officer at JetThoughts. Follow him on LinkedIn or GitHub.

Read next

Tell us whatyou need built

JetThoughts has been building software since 2008. Book a call, or write to sales@jetthoughts.com. You'll leave the call with a written one-page scope within 2 working days.

#01 Paul Keen
Paul KeenFounder

A 30-minute call; pick a time.