Using Rails Active Record List Types with Simple_Form

I declare a model with a type enumlike:

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 fine, and I get a selection filled with my enumerated types. When I execute @event.update(event_params)in my controller, I can check the db and see that the field has event_typebeen updated to the correct integer value.

However, when I revise the edit page, the selection shows nil. 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 is event_typetrue:

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

but the input selector is still empty, and does not show the "hospitality" as it should.

Any ideas would be much appreciated. :)

+4
6

. <%= f.input :event_type, collection: Event.event_types %>

? simple_form?

+11

enum_help gem. :

<%= f.input :event_type %>
+8

, . , , , event_type. event_type String, Integer:

class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      ...
      t.string :event_type
      ...
    end
  end
end

, . , , , . :

class Event < ActiveRecord::Base
  def self.types
    ['Special_Events', "On-Going", 'PTO', "Classroom"]
  end
  ...
end

:

<%= f.input :event_type, collection: Event.types, input_html: { autocomplete: 'off' }  %>

.

0

draper , . :

app/decorators/meter_decorator.rb

class MeterDecorator < Draper::Decorator
  delegate_all

  STATUS_MAPPING = {
    uninitialized: '未安装',
    good: '良好',
    broken: '故障',
    disabled: '禁止'
  }

  def status
    STATUS_MAPPING[object.status.to_sym]
  end
end

//_form.html.erb

<%= f.input :status, collection: MeterDecorator::STATUS_MAPPING, label_method: :last, value_method: :first, include_blank: false %>

//index.html.erb

<td><%= meter.decorate.status %></td>
0

Vincent : '0' is not a valid 'fieldname'

keys, stackoverflow: <%= f.input :event_type, collection: Event.event_types.keys %>

0

:

<%= f.input :event_type, collection: Event.event_types.keys,
            :selected => Event.event_types.keys[@event[:event_type].to_i], 
            input_html: { autocomplete: 'off' }  %>

, 2 :

  • : . Event.event_types.keys [@event [: event_type].to_i]. , , .:)
  • Set autocomplete: "off" to prevent Firefox from using to set the selector to the previous setting when the page reloads.

Alternative, simpler solutions would be welcome!

-1
source

All Articles