Make your Ruby on Rails applications more readable with Enums

Nicolás Galdámez
Unagi
Published in
2 min readJan 10, 2022
Illustration by Victoria Chepkasova from Ouch!

If you are a Ruby on Rails developer you´ll agree with me if I say that ActiveRecord is full of incredible features. It allows us to map our table with objects, persist data, query our tables, and do a lot more amazing things. One feature I love is enums.

An enumerative in Ruby on Rails is an attribute of type Integer that maps to a set of values.

In other words, we save an integer value in our database, but each value has a corresponding word in order to make the reference more readable.

Let’s look at an example to better understand what I’m talking about. Let’s imagine that we have a User model that could take one of two roles: administrator or operator. Let’s see how to easily handle roles with an enum.

The first thing we need to do is create the enum field as Integer in the user's table:

Then we declare the enum in our model:

Here’s where the magic happens. We map the integer values that are actually stored in the database, with the word we are going to use within our code. Yes, no more numbers to remember 😎.

And with this, we are ready to take advantage of all the benefits that enums give us:

Isn’t it cool? Thanks to this simple change, our code will be more readable and maintainable.

Do you use enums in your Rails projects? I would love to hear about your experience.

If you liked this article, you may be interested in one of these:

--

--

Nicolás Galdámez
Unagi
Editor for

Co-fundador de @unagi. Me gusta el cine, la lectura, y la ensalada de frutas.