---
title: 'What''s New in Edge Rails: Active Record enums'
teaser: Try out enums, a new data structure macro in Rails.
tags: web,rails
author: Prem Sichanugrist
published_on: 2014-04-01
---

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:

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

  def draft?
    status == 'draft'
  end

  def published?
    status == 'published'
  end
end
```

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

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

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

```ruby
# Query method
post.draft?
post.published?

# Action method
post.draft!
post.published!

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

There is one gotcha which you might notice since this is called [`enum`][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.

```ruby
# 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].

[Active Record Enum]: http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html
[enum]: https://en.wikipedia.org/wiki/Enumerated_type
[Rails 4.1.0.rc2]: http://weblog.rubyonrails.org/2014/3/25/Rails-4-1-rc2/
[documentation]: http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html
[release notes]: http://edgeguides.rubyonrails.org/4_1_release_notes.html#active-record-enums
[Ruby on Rails GitHub issues]: https://github.com/rails/rails/issues
