将字段名称作为参数传递给自定义验证方法 Rails 4 [英] Pass field name as parameter to custom validation method Rails 4
本文介绍了将字段名称作为参数传递给自定义验证方法 Rails 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个自定义验证方法:
I have a custom validation method:
def my_custom_validation
errors.add(specific_field, "error message") if specific_field.delete_if { |i| i.blank? }.blank?
end
目标是禁止包含 [""]
的参数通过验证,但我需要像这样调用这个方法:
The goal is to disallow parameters which contains [""]
pass through validation, but I need to call this method like:
validate :my_custom_validation #and somehow pass here my field names
例如:
validate :my_custom_validation(:industry)
推荐答案
由于您需要以这种方式验证多个属性,我会推荐一个像这样的自定义验证器:
Since you need to validate multiple attributes this way I would recommend a custom validator like so:
class EmptyArrayValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || "cannot be emtpy") if value.delete_if(&:blank?).empty?
end
end
然后验证为
validates :industry, empty_array: true
validates :your_other_attribute, empty_array: true
或者,如果您不想专门创建一个类,因为它只需要 1 个模型,您可以将其包含在模型本身中
Or if you don't want to specifically create a class because it is only needed for 1 model you could include this in the model itself
validates_each :industry, :your_other_attribute, :and_one_more do |record, attr, value|
record.errors.add(attr, "cannot be emtpy") if value.delete_if(&:blank?).empty?
end
这篇关于将字段名称作为参数传递给自定义验证方法 Rails 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文