简体   繁体   English

如何在 Rails 的验证中使用枚举?

[英]How to use an enum in a validation in Rails?

I have a model with an enum like this:我有一个 model 和这样的枚举:

enum health_company: {
    company_a: 0,
    company_b: 1,
    company_c: 2,
  }

and a validation that should allow health company "company_c" only if the job is of type "job_x":以及仅当工作类型为“job_x”时才允许健康公司“company_c”的验证:

validates:health_company, exclusion: { in: %i(company_c) }, unless: proc{ employee.last_job.job_x? }

This validation is not working.此验证不起作用。 What's the error?有什么错误? Is it even possible to exclude certain values from an enum based on a condition?甚至可以根据条件从枚举中排除某些值吗?

You must use rescue_from::ArgumentError in controller.您必须在 controller 中使用rescue_from::ArgumentError

rescue_from ::ArgumentError do |_exception|
  render json: { message: _exception.message }, status: :bad_request
end

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

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