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.
Now, let’s create a Product
with sold_out
status.
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.
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
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.
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.
References
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox