Using Rails Active Record enum types with Simple_Form

user3183015 picture user3183015 · Aug 14, 2014 · Viewed 12.3k times · Source

I declare a model with an enum type like:

class Event < ActiveRecord::Base
    enum event_type: { "special_event" => 0,
                       "pto"           => 1,
                       "hospitality"   => 2,
                       "classroom"     => 3
                       }

Then in my update view, I have a form with:

<%= simple_form_for @event do |f| %>   
    <%= f.input :event_type, collection: Event.event_types.keys %>  
    ... 
<% end %>

This works great, and I get a select populated with my enumerated types. When I perform the @event.update(event_params) in my controller, I can check the db and see that the event_type field has been updated to the correct integer value.

However, when I revisit the edit page, the select shows a nil value. If I check its value by adding a debug line to my form:

<%= f.input :event_type, collection: Event.event_types.keys %>  
<%= debug @event %>

I see that the value for event_type is correct:

--- !ruby/object:Event
attributes:
  ...
  event_type: '2'

but the input selector is still blank rather than showing "hospitality" as it should.

Any ideas would be greatly appreciated. :)

Answer

Vincent picture Vincent · Oct 9, 2014

this line worked just fine. <%= f.input :event_type, collection: Event.event_types %>

Do you have to manually set the selected value ? what's your version of simple_form ?