你如何使枚举与simple_form一起工作?

kof*_*rts 2 ruby enums ruby-on-rails simple-form

请考虑以下型号

  class Song < ActiveRecord::Base

      enum category: [:english, :french]

      enum file_type: [:mp3, :video]

      enum mood: [:sad, :happy]
    end
Run Code Online (Sandbox Code Playgroud)

我有一个表格

= simple_form_for(@song) do |f|

  = f.input :name
  = f.input :category, collection: Song.categories
  = f.input :file_type, collection: Song.file_types
  = f.input :mood, collection: Song.moods
Run Code Online (Sandbox Code Playgroud)

这里的问题是,当我编辑表单时,所选的值为nil,即选择框未选择设置的值,而是选择了空白。所以我想知道视图中是否有办法显示保存的枚举值?

谢谢!

cod*_*rhs 7

您需要将键传递给集合,而不是枚举。

= f.input :category, collection: Song.categories.keys