简体   繁体   English

Rails 4.2中的枚举验证不起作用

[英]Enum validation in Rails 4.2 doesn't work

My User model looks similar to this: 我的用户模型与此类似:

class User < ActiveRecord::Base
  enum type: [:admin, :reviewer, :super_admin ]
  validates :type, presence: true
  validates :type, inclusion: { in: User.types.keys }
end

When I submit anything outside the enum values, the validation doesn't stop the code from running, and I get a 500 error as a response with the following error: 当我提交枚举值之外的任何内容时,验证不会停止代码的运行,并且我收到500错误作为响应,并显示以下错误:

'something submitted' is not a valid type

If I submit a blank field, the validation works: 如果我提交空白字段,则验证有效:

"type": [
    "can't be blank",
    "is not included in the list"
]

What am I doing wrong? 我究竟做错了什么? My code looks identical to this answer 我的代码看起来与此答案相同

Rails enum doesn't have in-built validation. Rails enum没有内置验证。

The current focus of AR enums is to map a set of states (labels) to an integer for performance reasons. 出于性能原因,AR枚举的当前焦点是将一组状态(标签)映射到整数。 Currently assigning a wrong state is considered an application level error and not a user input error. 当前分配错误状态被认为是应用程序级别错误,而不是用户输入错误。 That's why you get an ArgumentError. 这就是为什么您会收到ArgumentError的原因。

You still can set nil or an empty string to the enum attribute without raising an error. 您仍然可以将nil或空字符串设置为enum属性,而不会引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM