简体   繁体   English

如何在Rails中编写对枚举的验证

[英]How to write validation for enum in rails

I have an enum in one of my model in my api 我的api中有一个模型中有一个枚举

enum pay_method: {
  cash: 0,
  card: 1
}

I want to have validation for this enum but i can not do that . 我想对此枚举进行验证,但我不能这样做。 I wrote a validation in my model for that but it did not take any effect 我为此在模型中编写了一个验证,但未生效

A validation for enum is not going to work, because Rails does not even allow to assign an enum variable with a wrong value. 枚举验证将无法进行,因为Rails甚至不允许分配带有错误值的枚举变量。 You will get an error before a validation. 验证之前,您会得到一个错误。 There is a good discussion of this behaviour here https://github.com/rails/rails/issues/13971 对于此行为,这里有一个很好的讨论https://github.com/rails/rails/issues/13971

rails enum functionality throws an error if the value submitted does not correspond to one of the keys or values of the hash. 如果提交的值与键或哈希值之一不对应,rails枚举功能将引发错误。 in this case it does not correspond to the key because the value you are submitting is a string so until here you are correct. 在这种情况下,它与密钥不对应,因为您要提交的值是一个字符串,因此直到此处正确为止。

the error still appear because enums are set before the validation process. 该错误仍然会出现,因为在验证过程之前已设置了枚举。 this could help you understand 这可以帮助您了解

@shippimg = Shippig.first
@shipping.status = 99
ArgumentError: '99' is not a valid status

rails developers say that programmers are the ones responsible taking care of what values they use assingning to enum attributes rails开发人员说,程序员是负责任的人,他们在维护枚举属性时使用哪些值

i have made a gem for validating enums inclusion. 我为验证枚举包含了一颗宝石。 this at least stops your server from crashing https://github.com/CristiRazvi/enum_attributes_validation 这至少可以阻止您的服务器崩溃https://github.com/CristiRazvi/enum_attributes_validation

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

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