Rails simple_form enum_help选择列表问题

use*_*827 1 enums ruby-on-rails simple-form ruby-on-rails-4

我有一个问题是使用simple_form在我的视图中创建工作选择枚举字段

这是我的代码:

# 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 %>
Run Code Online (Sandbox Code Playgroud)

这是输出HTML5数字(整数增量)字段而不是选择.

如果我改为:

...
<%= f.input :status, as: :select %>
or
<%= f.input :status, as: :radio_buttons %>
...
Run Code Online (Sandbox Code Playgroud)

它输出一个选择列表/单选按钮,标签为"是"和"否".当我尝试保存时,我得到#{integer}不是有效值错误.

任何帮助,将不胜感激.

Ric*_*eck 5

你最好用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 %>
Run Code Online (Sandbox Code Playgroud)

给出上下文,enum代表枚举器.

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

你获得yes/no和一个integer字段的原因是因为状态的"值"是数组[0,1].Rails无法区分.但是,使用上述方法,它可以.