Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Rails Active Record enum types with Simple_Form

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. :)

like image 662
user3183015 Avatar asked Aug 14 '14 21:08

user3183015


2 Answers

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 ?

like image 109
Vincent Avatar answered Nov 01 '22 05:11

Vincent


Vincent's solution gives me the error: '0' is not a valid 'fieldname'

I had to add keys as suggested in other stackoverflow post: <%= f.input :event_type, collection: Event.event_types.keys %>

like image 12
Daniel Garcia Avatar answered Nov 01 '22 04:11

Daniel Garcia