Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails serialized array validation

I need to validate email saving in email_list. For validation I have EmailValidator. But I cannot figure out how to use it in pair of validates_each. Are there any other ways to make validations?

class A < ActiveRecord::Base
  serialize :email_list
  validates_each :email_list do |r, a, v|
    # what should it be here? 
    # EmailValidator.new(options).validate_each r, a, v
  end
end
like image 722
gayavat Avatar asked Jun 02 '14 08:06

gayavat


Video Answer


1 Answers

validates_each is for validating multiple attributes. In your case you have one attribute, and you need to validate it in a custom way.

Do it like this:

class A < ActiveRecord::Base
   validate :all_emails_are_valid

   ...

   private
   def all_emails_are_valid
      unless self.email_list.nil?
         self.email_list.each do |email|
            if # email is valid -- however you want to do that
               errors.add(:email_list, "#{email} is not valid")
            end
         end
      end
   end
end

Note that you could also make a custom validator for this or put the validation in a proc on the validate call. See here.

Here's an example with a custom validator.

class A < ActiveRecord::Base

  class ArrayOfEmailsValidator < ActiveModel::EachValidator
    def validate_each(record, attribute, value)
      return if value.nil?
      value.each do |email|
        if # email is valid -- however you want to do that
          record.errors.add(attribute, "#{email} is not valid")
        end
      end
    end
  end

  validates :email_list, :array_of_emails => true

  ...

end

Of course you can put the ArrayOfEmailsValidator class in, i.e., lib/array_of_emails_validator.rb and load it where you need it. This way you can share the validator across models or even projects.

like image 134
gwcoffey Avatar answered Oct 04 '22 14:10

gwcoffey