Enter the field name as a parameter for the custom validation method. Rails 4

I have a special 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 containing [""]

validation, but I need to call this method, for example:

validate :my_custom_validation #and somehow pass here my field names

      

For example:

 validate :my_custom_validation(:industry) 

      

+3


source to share


1 answer


Since you need to validate multiple attributes this way, I would recommend a custom validator like this:

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

      

Then confirm as



validates :industry, empty_array: true
validates :your_other_attribute, empty_array: true

      

Or if you don't want to specifically create a class because only 1 model needs it, you can include that 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

      

+5


source







All Articles