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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何验证数组字段的成员?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个模型:
  1. class Campaign
  2.  
  3. include Mongoid::Document
  4. include Mongoid::Timestamps
  5.  
  6. field :name,:type => String
  7. field :subdomain,:type => String
  8. field :intro,:type => String
  9. field :body,:type => String
  10. field :emails,:type => Array
  11. end

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

你能给我一个指针吗?

解决方法

您可以定义自定义的ArrayValidator.在app / validators / array_validator.rb中放置以下内容
  1. class ArrayValidator < ActiveModel::EachValidator
  2. def validate_each(record,attribute,values)
  3. [values].flatten.each do |value|
  4. options.each do |key,args|
  5. validator_options = { attributes: attribute }
  6. validator_options.merge!(args) if args.is_a?(Hash)
  7.  
  8. next if value.nil? && validator_options[:allow_nil]
  9. next if value.blank? && validator_options[:allow_blank]
  10.  
  11. validator_class_name = "#{key.to_s.camelize}Validator"
  12. validator_class = begin
  13. validator_class_name.constantize
  14. rescue NameError
  15. "ActiveModel::Validations::#{validator_class_name}".constantize
  16. end
  17.  
  18. validator = validator_class.new(validator_options)
  19. validator.validate_each(record,value)
  20. end
  21. end
  22. end
  23. end

您可以在模型中使用它:

  1. class User
  2. include Mongoid::Document
  3. field :tags,Array
  4.  
  5. validates :tags,array: { presence: true,inclusion: { in: %w{ ruby rails } }
  6. end

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

猜你在找的Ruby相关文章