rails序列化数组验证

时间:2014-06-02 08:53:29

标签: ruby-on-rails validation activerecord serialization activemodel

我需要在email_list中验证电子邮件保存。为验证我有EmailValidator。但我无法弄清楚如何在validates_each对中使用它。还有其他方法可以进行验证吗?

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

2 个答案:

答案 0 :(得分:5)

validates_each用于验证多个属性。在您的情况下,您有一个属性,您需要以自定义方式验证它。

这样做:

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

请注意,您也可以为此创建自定义验证程序,或将验证放在validate调用的proc中。请参阅here

以下是自定义验证程序的示例。

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

当然,您可以将ArrayOfEmailsValidator类放入,lib/array_of_emails_validator.rb,然后将其加载到您需要的位置。这样,您可以跨模型甚至项目共享验证器。

答案 1 :(得分:2)

我最终得到了这个: https://gist.github.com/amenzhinsky/c961f889a78f4557ae0b

您可以根据rails guide编写自己的EmailValidator并使用ArrayValidator之类的内容:

validates :emails, array: { email: true }