Saving enum from select in Rails 4.1

后端 未结 8 1949
难免孤独
难免孤独 2020-11-28 02:31

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,         


        
相关标签:
8条回答
  • 2020-11-28 03:33

    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)) %>
    
    0 讨论(0)
  • 2020-11-28 03:36

    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) %>
    
    0 讨论(0)
提交回复
热议问题