ArgumentError:'1'不是有效的种类。枚举值未保存在数据库中

问题描述 投票:1回答:2

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

t.integer :kind

用户模型看起来像这样代表枚举:

Roles = ["admin","user"]

enum kind: Roles

在视图中,我一直在使用select标记来选择用户的角色,例如:

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

问题

当我保存表格时,我收到以下错误消息:

'1'不是有效的种类

我尝试检查在选择标记中发送的值的数据类型,它是整数。所以我不知道问题出在哪里。

ruby-on-rails ruby enums html-select
2个回答
3
投票

您在模型中没有用枚举类型定义的任何其他值都将无效。您仅可以创建一个值为adminuser的新记录。

尝试使用:

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

将使用模型中的枚举值和内部文本titlecased渲染选择标记。

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

# model
enum kind: %w[admin user]

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

-2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.