Jeremy Smith on February 12, 2015

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))
end

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

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

<%= form.select :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) %>

Need help building or maintaining a Rails app?

Jeremy is currently booked until mid-2023, but always happy to chat.

Email Jeremy