/ RAILS

How to get integer value from enum in Rails?

Getting value of integer stored in database for enum attribute on Rails ActiveRecord models can get tedious. This article will help understand how to fetch integer value of enum on ActiveRecord model in Rails.

Rails had introduced enums on ActiveRecord models.

Define enum on Model

Let’s take an example.

class Product < ApplicationRecord
    enum status: {
        sold_out:   0,
        active:     1,
        archived:   2
    }
end

Now, let’s create a Product with sold_out status.

$ Product.create(name: 'Sofa', status: :sold_out)

This stores value in database as integer corresponding to sold_out status.

Fetch string value of enum field

When we fetch any record from database, the column with enum defined over them, will be type casted to their corresponding value on read.

$ product = Product.last
$ puts product.status
# "sold_out"

As we can see, the status attribute on product already has string value.

Fetch integer value of enum field

Sometimes, we need the original value stored in database for such fields for some processing.

There are a couple of ways to fetch integer value of enum field.

1. Using pluralized enum hash

$ Product.statuses
# {
#      "sold_out" => 0,
#      "active"   => 1,
#      "archived" => 2
#  }

$ Product.statuses[product.status]
# 0

As we can see, this will output intended integer value.

2. Using before_type_cast attribute method

We can use *_before_type_cast methods available on ActiveRecord AttributeMethods.

$ product.status_before_type_cast
# 0

This will output raw value read from a database row. This will not have any impact of typecasting and deserialization performed by Rails on ActiveRecord object.

There’s one more method that can be used to obtain integer value of enum field on Rails ActiveRecord model.

$ product.read_attribute_before_type_cast('status')
# 0

References

akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee