DEV Community

Cover image for Enum validation in Ruby on Rails 7.1
JT Dev for JetThoughts LLC

Posted on

Enum validation in Ruby on Rails 7.1

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)

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Pay attention on validate: true in enum declaration.

We also can send additional rules to validation. For example:

validate: { allow_nil: true }
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)