120

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?

1
  • Where did the "input" method come from? Thanks
    – TPR
    Mar 10, 2022 at 15:47

9 Answers 9

221

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:

<select id="wine_color" name="wine[color]">
  <option value=""></option>
  <option value="red">red</option>
  <option value="white">white</option>
  <option value="sparkling">sparkling</option>
</select>

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] }
5
  • 8
    FWIW, I needed to make it f.select :color, Wine.colors.to_a.map { |w| [w[0].humanize, w[0]] } because w represented an array. Not sure why, but maybe this will help someone. Jun 28, 2015 at 1:09
  • 1
    using titleize might be a better idea if you have two or more words
    – Anwar
    Aug 10, 2015 at 4:46
  • 8
    the keys method returns an array so the to_a is redundant. Alternatively the select helper method takes a 2D array for options so you can just use to_a. Nov 23, 2015 at 19:15
  • What if an Invalid String is sent such as "ERROR_JUNK_Submission". Obviously there is no enum value such as this, and an exception is thrown. Where would we catch it?
    – FlyingV
    Nov 30, 2015 at 19:54
  • The model Wine has a enum called color enum color: [:red, :white, :sparkling]so the correct sentence is f.input :color, :as => :select, :collection => Wine.color.keys.to_a
    – hguzman
    Mar 20, 2020 at 2:14
41

No need converting the enum hash to array with to_a. This suffice:

f.select :color, Wine.colors.map { |key, value| [key.humanize, key] }
13

The accepted solution didn't work for me for the human readable, but I was able to get it to work like this:

<%= f.select(:color, Wine.colors.keys.map {|key| [key.humanize, key]}) %>

This was the cleanest, but I really needed to humanize my keys:

<%= f.select(:color, Wine.colors.keys) %>
3
  • 1
    rails 5 supports the cleanest way now
    – V-SHY
    Jan 5, 2017 at 3:38
  • @V-SHY, what is this way, can you explain? Jun 10, 2017 at 8:59
  • 2
    @ismailarilik, directly provide the keys as select option, <%= f.select(:color, Wine.colors.keys) %>
    – V-SHY
    Jun 11, 2017 at 6:24
13

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.

module EnumHelper

  def options_for_enum(object, enum)
    options = enums_to_translated_options_array(object.class.name, enum.to_s)
    options_for_select(options, object.send(enum))
  end

  def enums_to_translated_options_array(klass, enum)
    klass.classify.safe_constantize.send(enum.pluralize).map {
        |key, value| [I18n.t("activerecord.enums.#{klass.underscore}.#{enum}.#{key}"), key]
    }
  end

end

In your locale:

 en:
   activerecord:
     enums:
      wine:
        color:
          red:   "Red Wine"
          white:  "White Wine"

In your views:

 <%= f.select(:color, options_for_enum(@wine, :color)) %>
2
  • 1
    The edit makes the translation keys more readable by finding enums belonging to MultipleWordClassName under the rather more typical multiple_word_class_name rather than multiplewordclassname Sep 1, 2018 at 2:33
  • 1
    How about adding in a default for a graceful fallback: [I18n.t("activerecord.enums.#{klass.underscore}.#{enum}.#{key}", default: key.humanize), key] Also, remove the last humanize as it may distort capitalization if its multiple words
    – Peter P.
    Oct 2, 2018 at 13:29
6

If you use enum in Rails 4 then just call Model.enums:

f.select :color, Wine.colors.keys

To create HTML:

<select name="f[color]" id="f_color">
    <option value="red">red</option>
    <option value="white">white</option>
    <option value="sparkling"> sparkling </option>
</select>

Or add method in controller:

def update_or_create
    change_enum_to_i
    ....
end

def change_enum_to_i
    params[:f]["color"] = params[:f]["color"].to_i
end
5

If you need to handle the i18n based on the enum keys you can use:

<%= f.select :color, Wine.colors.keys.map {|key| [t("wine.#{key}"), key]} %>

and in the tranlations you can set the colors:

wine:
 red: Red
 white: White
5

Here is what worked for me, Rails 4+:

class Contract < ApplicationRecord

enum status: { active:  "active", 
               ended: "active", 
               on_hold: "on_hold", 
               terminated:  "terminated", 
               under_review:  "under_review" , 
               unknown: "unknown" 
              }


end

in my _form.html.erb , I have this:

  <div class="field">
    <%= form.select :status, Contract.statuses.keys, {}%>
  </div>

test from Console after adding a record:

2.3.0 :001 > Contract.last.status
  Contract Load (0.2ms)  SELECT  "contracts".* FROM "contracts" ORDER BY "contracts"."id" DESC LIMIT ?  [["LIMIT", 1]]
 => "active"
1

Here's my solution (my roles have underscores in them like "sales_rep"), and for some reason this was how I needed to get a blank option to work (with simpleform?):

In ApplicationHelper:

def enum_collection_for_select(attribute, include_blank = true)
  x = attribute.map { |r| [r[0].titleize, r[0]] }
  x.insert(0,['', '']) if include_blank == true
  x
end

Then in my form:

<%= f.input :role, collection: enum_collection_for_select(User.roles), selected: @user.role %>
0

for me the following worked as well:

= f.input :color, collection: Wine.colors.keys.map{ |key| [key.humanize, key] }, include_blank: false

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.