I am using the enums in Rails 4.1 to keep track of colors of wine.
Wine.rb
class Wine < ActiveRecord::Base
enum color: [:red, :white, :sparkling]
end
In my view, I generate a select so the user can select a wine with a certain color
f.input :color, :as => :select, :collection => Wine.colors
This generates the following HTML:
<select id="wine_color" name="wine[color]">
<option value=""></option>
<option value="0">red</option>
<option value="1">white</option>
<option value="2">sparkling</option>
</select>
However, upon submitting the form, I receive an argument error stating '1' is not a valid color
. I realize this is because color
must equal 1
and not "1"
.
Is there a way to force Rails to interpret the color as an integer rather than a string?
If you need to handle the i18n based on the enum keys you can use:
and in the tranlations you can set the colors:
Alright, so apparently, you shouldn't send the integer value of the enum to be saved. You should send the text value of the enum.
I changed the input to be the following:
f.input :color, :as => :select, :collection => Wine.colors.keys.to_a
Which generated the following HTML:
Values went from "0" to "red" and now we're all set.
If you're using a regular ol' rails text_field it's:
f.select :color, Wine.colors.keys.to_a
If you want to have clean human-readable attributes you can also do:
f.select :color, Wine.colors.keys.map { |w| [w.humanize, w] }
If you use enum in Rails 4 then just call
Model.enums
:To create HTML:
Or add method in controller:
I just put together an EnumHelper that I thought I'd share to help people who need more customised enum labels and locales for your enum selects.
In your locale:
In your views:
Here is what worked for me, Rails 4+:
in
my _form.html.erb
, I have this:test from Console after adding a record:
The accepted solution didn't work for me for the human readable, but I was able to get it to work like this:
This was the cleanest, but I really needed to humanize my keys: