【问题标题】:how do you make enums work with simple_form?你如何使枚举与 simple_form 一起工作?
【发布时间】:2017-12-20 09:51:59
【问题描述】:

请考虑以下型号

  class Song < ActiveRecord::Base

      enum category: [:english, :french]

      enum file_type: [:mp3, :video]

      enum mood: [:sad, :happy]
    end

我有一个表格

= 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

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

谢谢!

【问题讨论】:

  • 你可以试试。 collection: Song.categories.keys?
  • 谢谢你这样做。把它放在答案中,我会接受它。

标签: ruby-on-rails ruby enums simple-form


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-16
    • 2010-10-25
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    相关资源
    最近更新 更多