我声明一个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)
但输入选择器仍然是空白而不是应该显示"好客".
任何想法将不胜感激.:)