简体   繁体   中英

How to write validation for enum in rails

I have an enum in one of my model in my 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. You will get an error before a validation. There is a good discussion of this behaviour here 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. 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

i have made a gem for validating enums inclusion. this at least stops your server from crashing https://github.com/CristiRazvi/enum_attributes_validation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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