gpt4 book ai didi

ruby-on-rails - 将字段名称作为参数传递给自定义验证方法 Rails 4

转载 作者:数据小太阳 更新时间:2023-10-29 07:49:52 25 4
gpt4 key购买 nike

我有一个自定义验证方法:

def my_custom_validation
errors.add(specific_field, "error message") if specific_field.delete_if { |i| i.blank? }.blank?
end

目标是禁止包含 [""] 的参数通过验证,但我需要像这样调用此方法:

validate :my_custom_validation #and somehow pass here my field names

例如:

 validate :my_custom_validation(:industry) 

最佳答案

由于您需要以这种方式验证多个属性,因此我建议使用这样的自定义验证器:

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

或者,如果您不想专门创建一个类,因为只有一个模型需要它,您可以将其包含在模型本身中

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

关于ruby-on-rails - 将字段名称作为参数传递给自定义验证方法 Rails 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25685746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com