What is an Enum in Rails?

An Enum (enumeration) in Ruby on Rails is a feature that allows developers to define a set of symbolic values mapped to either integers or strings.

This means that instead of creating boolean columns like "active", "inactive", or "banned", for example, for the users table, we can create either an integer or a string column status and store representations such as 0, 1, and 2 or "active", "inactive", and "banned" respectively. This practice enhances performance, consistency, and readability in applications.

Note: Integer-based queries are faster and more memory-efficient than string-based queries.

Enums are particularly useful in scenarios where you have a finite set of possible values for a given attribute. Common use cases include user roles, order statuses, publication states, and more.

Why Use Enums?

Rails’ enum feature brings several advantages:

Readability: Using symbolic names (:active, :inactive) instead of raw numbers makes code more understandable.

Database Integrity: Enums enforce constraints, ensuring only predefined values are stored.

Automatic Query Methods: Rails generates helper methods to work seamlessly with enum attributes.

Consistency: Prevents invalid states by limiting possible values.

Let’s take an example of an e-commerce system where an Order can have statuses such as "pending", "shipped", "delivered", and "cancelled". Instead of storing these as booleans, we define them as Enums (either as integers or as strings).

Integer Enums

class Order < ApplicationRecord
  enum :status, { pending: 0, shipped: 1, delivered: 2, cancelled: 3 }
end

String Enums

class Order < ApplicationRecord
  enum :status, { pending: "pending", shipped: "shipped", delivered: "delivered", cancelled: "cancelled" }
end

Note: We can either define enums as integers or as strings, however, both have advantages or disadvantages of their own. You can read this article "Integer Enums vs. String Enums in Rails: Which One Should You Use?" to know which one to use when for your Rails application.

This allows us to query orders efficiently and write expressive code.

order = Order.new(status: :pending)
order.status  # => "pending"
order.pending? # => true
order.delivered! # Updates status to "delivered"

This concise and intuitive syntax is what makes Enums a powerful feature in Rails.