[英]How do I do conditional validation in ActiveRecord with n conditions?
I am providing a web service to be called by external companies.我正在提供 web 服务,供外部公司调用。 The required data covers several models including person, address etc. I want to validate the received data conditionally based upon some fields within the request.所需数据涵盖多个模型,包括人员、地址等。我想根据请求中的某些字段有条件地验证接收到的数据。 I will eventually have many differing sets of validation data, although currently I only have one and I am about to add the second.我最终将拥有许多不同的验证数据集,尽管目前我只有一个并且我即将添加第二个。
My current model looks something like this我目前的 model 看起来像这样
class Person < ActiveRecord::Base
validates_length_of :first_name, :within => 1..32, :allow_blank => true
...
...
end
Conceptually my model now needs to do something like this.从概念上讲,我的 model 现在需要做这样的事情。
class Person < ActiveRecord::Base
validate :first_name?
def first_name?
if country == 'UK'
if company_name == 'ABC'
validates_length_of :first_name, :within => 1..32
else if company_name == 'DEF'
validates_length_of :first_name, :within => 2..20
end
else if country == 'DE'
if company_name == 'ABC'
validates_length_of :first_name, :within => 1..32
else if company_name == 'DEF'
validates_length_of :first_name, :within => 2..20
end
end
end
This would obviously work fine for 2 companies/countries but will not work well as the number of companies and/or countries increases.这显然适用于 2 家公司/国家,但随着公司和/或国家数量的增加,效果不佳。 I am now considering keeping the validation data either in the database or in a YAML file and then performing the validations manually for each field based upon the minimum, maximum, format values stored externally from the model.我现在正在考虑将验证数据保存在数据库或 YAML 文件中,然后根据从 model 外部存储的最小、最大格式值手动为每个字段执行验证。
I am thinking that I could store the validation data in a structure similar to the following我在想我可以将验证数据存储在类似于以下的结构中
country: UK companyname: ABC field: first_name minimum_length: 2 maximum_length: 20 required: true field: middle_name minimum_length: 1 maximum_length: 10 field: email_address minimum_length: 10 format: /someregexforemail addresses/ companyname: DEF field ... country: DE companyname: XYZ field: ....
and so on.等等。
I could then load this validation data and use this within my own hand-rolled validator.然后我可以加载这个验证数据并在我自己的手动验证器中使用它。
Has anyone done similar things in the past and what methods did you use?过去有没有人做过类似的事情,你使用了什么方法? I am particularly interested to know how you approached the following.我特别想知道您是如何处理以下问题的。
I did something similar with phone numbers.我对电话号码做了类似的事情。 Your approach is very similar to what I did myself.您的方法与我自己的方法非常相似。 To answer your questions:要回答您的问题:
Did that help you?这对你有帮助吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.