【问题标题】:Rails plug and play validationsRails 即插即用验证
【发布时间】:2016-07-02 11:43:13
【问题描述】:

这是我的例子

class User < ActiveRecord::Base
  validates_with EmailValidator
end

class EmailValidator < ActiveModel::Validator
  def validate(record)
    if record != someregex
      record.errors.add(:email, 'invalid email')
    end
  end
end

现在我可以将这个EmailValidator 用于任何型号。但我的要求是验证它对于特定模型的独特性和存在性。

如果我能做到这一点,我可以使用这个EmailValidator 进行任何具有独特功能的模型电子邮件验证,存在。

那我就可以实现更可复用的Validator了。

【问题讨论】:

    标签: ruby-on-rails validation ruby-on-rails-4 rails-activerecord


    【解决方案1】:

    您可以通过将验证器重写为 EachValidator 来做到这一点:

    class EmailValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        if attribute !~ someregex
          record.errors.add attribute, (options[:message] || 'invalid email')
        end
      end
    end
    

    然后在你的模型中:

    validates :email, email: true, uniqueness: true, presence: true
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 2015-04-20
      • 2012-02-11
      • 2015-12-15
      • 1970-01-01
      • 2013-08-01
      相关资源
      最近更新 更多