微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – 如何验证数组字段的成员?

我有这个模型:
class Campaign

  include Mongoid::Document
  include Mongoid::Timestamps

  field :name,:type => String
  field :subdomain,:type => String
  field :intro,:type => String
  field :body,:type => String
  field :emails,:type => Array
end

现在我想验证电子邮件数组中的每个电子邮件格式正确.我读了Mongoid和ActiveModel :: Validations文档,但是我没有找到如何做到这一点.

你能给我一个指针吗?

解决方法

您可以定义自定义的ArrayValidator.在app / validators / array_validator.rb中放置以下内容
class ArrayValidator < ActiveModel::EachValidator
  def validate_each(record,attribute,values)
    [values].flatten.each do |value|
      options.each do |key,args|
        validator_options = { attributes: attribute }
        validator_options.merge!(args) if args.is_a?(Hash)

        next if value.nil? && validator_options[:allow_nil]
        next if value.blank? && validator_options[:allow_blank]

        validator_class_name = "#{key.to_s.camelize}Validator"
        validator_class = begin
          validator_class_name.constantize
        rescue NameError
          "ActiveModel::Validations::#{validator_class_name}".constantize
        end

        validator = validator_class.new(validator_options)
        validator.validate_each(record,value)
      end
    end
  end
end

您可以在模型中使用它:

class User
  include Mongoid::Document
  field :tags,Array

  validates :tags,array: { presence: true,inclusion: { in: %w{ ruby rails } }
end

它将从阵列中的每个元素验证数组散列中指定的每个验证器.

原文地址:https://www.jb51.cc/ruby/272390.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐