Working with enums in Rails

With the release of Rails 4, a lot of things have changed, new features were added including security issues, active record extensions, concerns, and so much more. But something I recently found was the introduction of enums which are basically a set of attributes which map into integer to the database.

In other words, what an enum does is it associates a symbol with an integer, which by default is the position of the element. For example:

class User < ActiveRecord::Base  
 enum role: [:member, :admin, :superadmin]

So in that case :member would be 0, admin would be 1 and so on. But an enum is more helpful than that, it builds up some methods for you to use them right away, such as:

# user.update! status: 0
user.member? # => true  
user.role # => "member"  

In fact there is more than that, you can scope the enums for querying:

User.member # this returns an array of users with a role of member  
User.admin # this returns an array of users with a role of admin  

But wait there is more you can create records using the enum, something like:

#By scope
User.member.create({#hash of attributes})

#By attributes
User.create(role: User.roles[:member])  

Notice the roles to access the enum which is a hash of the enum symbol names to the index of their placement in the original array.


As you can see enums save us a lot of time defining scopes, and some handy methods. Just be aware of not using same method names for your active record class as you may run in conflicts.

I know I'll be using these more often, and you might want to take a deeper look at them. The documentation is really good.