Saving enum from select in Rails 4.1

后端 未结 8 1972
难免孤独
难免孤独 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:10

    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] }

提交回复
热议问题