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 integers.

This means that instead of storing string-based values like "active", "inactive", or "banned", we use integer representations such as 0, 1, and 2. This practice enhances performance, consistency, and readability in applications.

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: ** **Performance: Integer-based queries are faster and more memory-efficient than string-based queries.

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 strings, we define them as Enums.

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

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.