March 31, 2015 by Daniel P. Clark

Rails 4’s Awesome enums

In Rails 4 enum was introduced to support a feature that people were building by hand or by gem.  What enum does for you is it associates a symbol list for you to reference which will be stored in the database as an integer.  So :cow could be 0 and :dog could be 1 in an enum of [:cow, :dog] .  But enum is far more helpful that that.  It builds scopes and boolean checker methods.

For example.  Lets create a Flower object and we’ll have kinds and colors as enums.

First we generate the model.

Then we update app/models/flower.rb

Make sure you migrate.

And now all the hard work has been done for you.

You can create a blue rose in two different ways.  With scopes, or with attributes.

As you can see I used the plural name on the class of Flower for setting the attribute values.  The plural named method is a Hash of the enum symbol names to the index of their placement in the originally defined Array.  So kinds[:rose] will return 0 for the attribute to be written to the database since it was the first item in the enum defined.

And you can access them by the same scopes (and scopes work in any order)

As I had mentioned earlier enum will add boolean checkers for every single enum option.

And you can forcefully change them with a bang method.

If you look at the record’s attributes you can see that the enum‘s are stored as integers.  The integers are the index of the Array in which you declared the enum.  So you can add new items to the end of the enum Array, but don’t change the ordering.

To check whether an enum value has been set for any of the enum fields just use a boolean check on the enum name.

Summary

As you can see enum has saved us a lot of work by defining many scopes and helper methods.  This comes in to be pretty handy.  As a consequence though you can’t use conflicting names between any enum or ActiveRecord methods.  So you may have to be clever for some names to use.  I really like having the convenience that enum adds.  And now you have this power tool in your tool set! ^_^

Please share, I’d love to hear about them.  Please feel free to comment, share, subscribe to my RSS Feed, and follow me on twitter @6ftdan!

God Bless!
-Daniel P. Clark

Image by Hernán García Crespo via the Creative Commons Attribution 2.0 Generic License.

#activerecord#boolean#database#db#enum#helper#rails#rails 4#scope#scopes