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

Ole*_*sky 3 ruby validation ruby-on-rails web ruby-on-rails-4

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

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

目标是禁止包含[""]传递验证的参数,但我需要调用此方法,如:

validate :my_custom_validation #and somehow pass here my field names
Run Code Online (Sandbox Code Playgroud)

例如:

 validate :my_custom_validation(:industry) 
Run Code Online (Sandbox Code Playgroud)

eng*_*nky 6

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

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
Run Code Online (Sandbox Code Playgroud)

然后验证为

validates :industry, empty_array: true
validates :your_other_attribute, empty_array: true
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)