【问题标题】:Inheritance with Custom Validators Ruby on Rails使用自定义验证器继承 Ruby on Rails
【发布时间】:2013-06-24 00:54:42
【问题描述】:

我试图在 Ruby on Rails 中创建一个可以扩展的自定义验证器类。但是,我无法让它同时使用子类和超类的验证。 这个例子将阐明我想要实现的目标:

超类

class NameValidator < ActiveModel::EachValidator
   def validate_each (record, attribute, value)

       #Checks to see if the incoming string is free of any numerical characters
        if value.match(/\A[+-]?\d+\Z/)
        record.errors[attribute] << "String must contain no numerical characters"
        end
   end
end

子类

class SevenNameValidator < NameValidator

     def validate_each (record, attribute, value)

         # Checks and only allows 7 character strings to be validated
         if value.length != 7
            record.errors[attribute] << "String must be 7 characters exactly"
         end
     end
 end

模型类

class User < ActiveRecord::Base
  attr_accessible :firstname

  validates :firstname, :seven_name => true

end

因此,如果测试字符串“hello”,则会出现错误 =>“字符串必须完全是 7 个字符”

但是,如果测试字符串“hello77”,则验证成功。

它不应该先从 NameValidator 检查它是否有数字?如果没有,我怎样才能让继承在自定义验证器中工作?我需要在我的验证器类中使用方法吗?一个例子将不胜感激,我搜索了很多,但我找不到自定义验证器的例子。

【问题讨论】:

  • 您可能希望在 SevenNameValidator 的 validate_each 中使用 super

标签: ruby-on-rails ruby ruby-on-rails-3 inheritance custom-validators


【解决方案1】:

在子类中调用super

class SevenNameValidator < NameValidator

     def validate_each (record, attribute, value)

         # Checks and only allows 7 character strings to be validated
         if value.length != 7
            record.errors[attribute] << "String must be 7 characters exactly"
         else
           #call super to trigger super class method
           super 
         end
     end
 end

【讨论】:

    【解决方案2】:

    我认为您的正则表达式可能有问题。如果您尝试将任何字符串与数字匹配,那么您现在应该有类似 /\A\D*\d+\D*\z/ 的内容,您正在匹配大量我认为您不想要的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      • 2012-04-29
      • 2013-04-16
      • 2023-04-06
      • 2012-07-23
      • 1970-01-01
      相关资源
      最近更新 更多