What's new in edge Rails: Active Record enums

In an Active Record model, usually you will have a column that can only have a set of pre-defined values (such as a status column). Normally, you would define a constant for those values as well as several helper methods like the following example:

class Post < ActiveRecord::Base
  STATUS = %w(draft published)

  def draft?
    status == 'draft'

  def published?
    status == 'published'

In the upcoming Rails 4.1.0, the core team has added ActiveRecord::Enum support, which help clean up this type of attribute. With enum, you can rewrite the above code as:

class Post < ActiveRecord::Base
  enum status: %w(draft published)

With this single line of code, Rails will generate several helper methods for you:

# Query method

# Action method

# List of statuses and their corresponding values in the database.

There is one gotcha which you might notice since this is called enum: you will need to update your database column to be an integer value. Rails will do implicit mapping between the integer value and the index of the value in the array automatically.

# Given that the `status` column has default value of '0'
post = Post.new
post.status # => "draft"

post.status = 'published'
post.published? # => true
post.save! # => UPDATE posts SET status = '1' WHERE id = '1'

If you are interested in trying out this feature, you can try it today on Rails 4.1.0.rc2. Be sure to read the documentation and release notes for more information. If you find any bugs, please do not forget to report them on Ruby on Rails GitHub issues.


Sharpen your programming skills by completing coding exercises that are reviewed by other developers at Upcase today.