【问题标题】:How to use active_enum enumarate in an HTML select element?如何在 HTML 选择元素中使用活动枚举枚举?
【发布时间】:2014-07-27 13:10:12
【问题描述】:

我在我的 Rails 4 应用程序中使用 active_enum gem。 https://github.com/adzap/active_enum

gem 'active_enum'

在我的模型中,我有一个枚举:

class Meeting < ActiveRecord::Base
  enumerate :participant_type do
    value 0 => 'Juniors'
    value 1 => 'Senior'
    value 2 => 'Administration'
  end
end

如何在表单选择元素中使用这些值?

我尝试了以下方法,但出现运行时错误:

= f.select :participant_type, Loan.participant_type

undefined method `participant_type' for #<Class:0x007f8803581050>

【问题讨论】:

    标签: ruby-on-rails ruby active-enum


    【解决方案1】:

    将 Participant 类型作为扩展 ActiveEnum::Base 的单独类并尝试.to_select 方法。

    = f.select :participant_type, ParticipantType.to_select, required: true
    

    如果是 Active Record Enum,请尝试以下操作:

    它是participant_types 的复数形式,如docs 中所述。

    = f.select :participant_type, Meeting.participant_types, required: true
    

    【讨论】:

    • 不,这是在 ActiveRecord::Enum 中烘焙的。在这种情况下,我不使用那些。我正在使用active_enum 一个完全独立的宝石。 :)
    • 选项很少——创建一个单独的类并使用 to_select,或者使用这里提到的表单助手github.com/adzap/active_enum#form-helpers
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多