ruby-on-rails – 如何验证数组字段的成员?
发布时间:2020-12-16 19:59:14 所属栏目:百科 来源:网络整理
导读:我有这个模型: 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 = Arrayend 现在我想验
我有这个模型:
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 它将从阵列中的每个元素验证数组散列中指定的每个验证器. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |