I have an enum on my class like this:
class Post < ActiveRecord::Base
enum status: [ :unconfirmed, :corroborated, :confirmed ]
end
I am using Simple Form, and I want to produce a dropdown menu in my form partial.
This is what I have now:
<%= 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 %>
When I create a new Post
record, I get this error:
Completed 500 Internal Server Error in 20ms
ArgumentError - '2' is not a valid status:
When I do Post.statuses
in my console, I get this:
> Post.statuses
=> {"unconfirmed"=>0, "corroborated"=>1, "confirmed"=>2}
How can I do what I need with this enum
?
You need to use keys
of enum
as name
and value
in collection. Meaning, you need to use Post.statuses.keys
as collection:
<% statuses = Post.statuses %>
<%= f.input_field :status, label: "Status", collection: statuses.keys, selected: :corroborated %>