我的课堂上有一个这样的枚举:
class Post < ActiveRecord::Base
enum status: [ :unconfirmed, :corroborated, :confirmed ]
end
我正在使用Simple Form,我希望以部分形式生成一个下拉菜单。
这就是我现在所拥有的:
<%= simple_form_for(@post, html: {class: 'form-horizontal' }) do |f| %>
<%= f.error_notification %>
<%= f.input_field :parent_id, as: :hidden %>
<div class="field">
<% if can? :manage, @post %>
<%= f.input_field :status, label: "Status", collection: Post.statuses, selected: Post.statuses[:corroborated] %>
<% end %>
</div>
<%= f.input :title, placeholder: "Enter Title" %>
<%= f.input :photo %>
<%= f.input :file %>
<%= f.input :body %>
<div class="report-submit">
<%= f.button :submit %>
</div>
<% end %>
当我创建新的Post
记录时,我收到此错误:
Completed 500 Internal Server Error in 20ms
ArgumentError - '2' is not a valid status:
当我在我的控制台中Post.statuses
时,我得到了这个:
> Post.statuses
=> {"unconfirmed"=>0, "corroborated"=>1, "confirmed"=>2}
如何使用此enum
来完成我需要的工作?
答案 0 :(得分:2)
您需要在keys
enum
中使用name
作为value
和Post.statuses.keys
。意思是,您需要使用<% statuses = Post.statuses %>
<%= f.input_field :status, label: "Status", collection: statuses.keys, selected: :corroborated %>
作为集合:
{{1}}
答案 1 :(得分:0)
要有一个选择框我想:
<%= f.input_field :status, label: "Status", collection: Post.statuses, selected: Post.statuses[:corroborated] %>
需要改为:
<%= f.select :status, options_for_select(Post.statuses.collect { |s| [s[0].humanize, s[0]] }, selected: Post.statuses[:corroborated])%>
您还可以将对象的状态作为选定选项吗?像这样:
<%= f.select :status, options_for_select(Post.statuses.collect { |s| [s[0].humanize, s[0]] }, selected: post.status)%>