ArgumentError: '1' is not a valid kind. Enum value not saving in database

ArgumentError: '1' is not a valid kind. Enum value not saving in database

我的用户模型有一个属性:

t.integer :kind

用于表示枚举的用户模型看起来像这样:

Roles = ["admin","user"]

enum kind: Roles

在视图中,我一直使用一个select标签,来select用户喜欢的角色:

= f.label :kind, "Kind:"
= f.select :kind, options_for_select(User::Roles.map.with_index{|role,index| [role.titlecase,index]})

问题

当我保存表格时出现错误:

'1' 不是有效种类

我尝试检查 select 标记中发送的值的数据类型,它是整数。所以我不知道是什么问题。

option_for_select 应该是 User::Roles.map.with_index{|role,index| [role.titlecase,role.titlecase]}

您的模型中类型枚举定义中未说明的任何其他值都将无效。您只需创建一个值为 adminuser.

的新记录

试试:

f.select :kind, options_for_select(User::Roles.map { |role| [role.titlecase, role] })

它使用模型中的枚举值和内部文本 titlecased.

呈现 select 标签

注意,您不要将用户类型定义存储在其他任何地方。如果您在模型中定义它,您可以随后将其作为方法 class 调用:

# model
enum kind: %w[admin user]

# view
User.kinds.keys.map { |role| [role.titlecase, role] }