Active Record enum form select

I’ve been enjoying the new Active Record enums in Rails 4.1. But I haven’t found a nice way to represent the enum options in a form select. So, I wrote a couple small helper methods that I put in application_helper.rb:

def options_from_enum_for_select(instance, enum)
  options_for_select(enum_collection(instance, enum), instance.send(enum))

def enum_collection(instance, enum)
  instance.class.send(enum.to_s.pluralize) { |key| [key.humanize, key] }

Now, instead of hard-coding the enum options in the form select, I can do this:

<%= :status, options_from_enum_for_select(@faq, :status) %>

Or, when I’m using simple_form, I can use this:

<%= form.input :status, collection: enum_collection(@faq, :status) %>

Posted February 12, 2015 at 1:38 pm