Rails simple_form enum_help select 列出问题

Rails simple_form enum_help select lists issue

我在使用 simple_form

为我的视图中的枚举字段创建工作 select 时遇到问题

这是我的代码:

# In model project.rb

enum status: [:draft, :published]

# In view _form.html.erb

<%= simple_form_for @project do |f| %>

  <%= f.input :title %>

  <%= f.input :status %>

  ...

<% end %>

这是输出 HTML5 数字(整数增量)字段而不是 select。

如果我改成:

...
<%= f.input :status, as: :select %>
or
<%= f.input :status, as: :radio_buttons %>
...

它输出带有标签 "Yes" 和 "No" 的 select 列表/单选按钮。当我尝试保存时,出现 #{integer} is not a valid value 错误。

如有任何帮助,我们将不胜感激。

你最好使用 collection_select / collection_radio_buttons:

<%= simple_form_for @project do |f| %>

  <%= f.input :status, collection: Project.statuses, label_method: :first, value_method: :first, include_blank: false %>
  <%= f.input :status, collection: Project.statuses, label_method: :first, value_method: :first, as: :radio_buttons %>

<% end %>

为了提供上下文,enum 代表 enumerator

它将您的选项映射到数值 [0,1],允许您简洁地定义属性的预烘焙选项。

您得到 yes/nointeger 字段的原因是状态的 "value" 是数组 [0,1]。 Rails 无法区分。但是用上面的方法,可以.