A Simple Guide to Enum’s with Rails

black and white dappled light on leaves

What

An enum is a special data type that allows you to declare and query data with string variables but stores an integer in the database. You can think of an enum as being able to set a variable to a value (for Ruby on Rails, its an integer value). For example, if you want a status column in your database model, you could set the status to enum type and store your possible statuses started, in progress, and complete, as 0, 1, and 2.

Why

Not only does this let developers write more semantic code, but it’s also more space-efficient, less bug-prone, and easy to update down the road!

When

I like to think of an enum as a combination of a boolean and a string. If you have an attribute that has a finite number of possible values, that will likely have to be updated, this could be a good place to use an enum. Here are some examples:

  • Status enum (not started: 0, in progress: 1, complete: 2)
  • Direction enum (north: 0, south: 1, east: 2, west: 3)
  • Suit enum (hearts: 0, spades: 1, diamonds: 2, clubs: 3)

How

In Ruby on Rails

  1. Set up your model with the enum attribute set to an integer

2. In the model file, list the characteristics of the attribute. Note that you can let Rails set default values but can declare the values as well.

That’s it! Rails makes it super easy to set up an enum.

  • Declare or change attributes using the string, the int, even a bang
  • Get the value or get whether the instance is a specific status
  • Find all objects with a specific value
  • Enums can make writing forms a breeze

As always, thanks for reading!! For more on Enums check out some of the resources below 📚