我有这个模型:
- 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
它将从阵列中的每个元素验证数组散列中指定的每个验证器.