使用带有Simple_Form的Rails Active Record枚举类型

use*_*015 9 enums ruby-on-rails simple-form

我声明一个enum类型如下的模型:

class Event < ActiveRecord::Base
    enum event_type: { "special_event" => 0,
                       "pto"           => 1,
                       "hospitality"   => 2,
                       "classroom"     => 3
                       }
Run Code Online (Sandbox Code Playgroud)

然后在我的更新视图中,我有一个表单:

<%= simple_form_for @event do |f| %>   
    <%= f.input :event_type, collection: Event.event_types.keys %>  
    ... 
<% end %>
Run Code Online (Sandbox Code Playgroud)

这很好用,我得到一个填充了我的枚举类型的选择.当我@event.update(event_params)在我的控制器中执行时,我可以检查数据库并看到该event_type字段已更新为正确的整数值.

但是,当我再次访问编辑页面时,select会显示一个nil值.如果我通过在表单中​​添加调试行来检查其值:

<%= f.input :event_type, collection: Event.event_types.keys %>  
<%= debug @event %>
Run Code Online (Sandbox Code Playgroud)

我看到值event_type是正确的:

--- !ruby/object:Event
attributes:
  ...
  event_type: '2'
Run Code Online (Sandbox Code Playgroud)

但输入选择器仍然是空白而不是应该显示"好客".

任何想法将不胜感激.:)

Vin*_*ent 18

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 ?


Sta*_*ers 8

使用enum_help gem.让你这样做:

<%= f.input :event_type %>
Run Code Online (Sandbox Code Playgroud)


小智 7

Vincent的解决方案给了我错误: '0' is not a valid 'fieldname'

我必须keys按照其他stackoverflow帖子的建议添加: <%= f.input :event_type, collection: Event.event_types.keys %>


小智 6

我也被这个卡住了。我需要为我的枚举命名,这样它们就不会在我使用的 snake_case 中显得那么古怪。我使用 to_a 获取 ruby​​ 哈希并将其转换为数组,然后使用 collect 以我需要的格式返回一个新数组。

collection: Event.event_type.to_a.collect{|c| [c[0].titleize, c[0]]}
Run Code Online (Sandbox Code Playgroud)

希望这会帮助其他人。


use*_*015 -1

经过更多研究,我提出了以下解决方案:

<%= f.input :event_type, collection: Event.event_types.keys,
            :selected => Event.event_types.keys[@event[:event_type].to_i], 
            input_html: { autocomplete: 'off' }  %>
Run Code Online (Sandbox Code Playgroud)

所以,我必须做两件事:

  • 使用 :selected 设置选择器的值。这需要使用繁琐的语法 Event.event_types.keys[@event[:event_type].to_i] 来设置选择值。我很想听听是否有更简单的语法可以使用。:)
  • 设置 autocomplete: 'off' 以防止 Firefox 在页面重新加载时将选择器设置为之前的设置。

替代的、更简单的解决方案将受到欢迎!