Validation of a serialized rail array

I need to check the storage of email in the email_list element. For verification, I have EmailValidator. But I cannot figure out how to use it in a validates_each pair. Are there other ways to do 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 
+6
source share
2 answers

I ended up with this: https://gist.github.com/amenzhinsky/c961f889a78f4557ae0b

You can write your own EmailValidator according to the rails guide and use ArrayValidator as:

 validates :emails, array: { email: true } 
+2
source

validates_each designed to validate multiple attributes. In your case, you have one attribute, and you need to check it in your own 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 

Please note that you can also make a special validator for this or put a check in proc to call validate . See here .

Here is 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. Thus, you can use the validator for models or even projects.

+5
source

Source: https://habr.com/ru/post/970166/


All Articles