如何在验证器中获取对象上下文?

时间:2016-10-17 11:48:40

标签: validation ruby-on-rails-4

使用过的验证器:

  validates :address, :allow_nil => true, :allow_blank => true,
            uniqueness: {
                scope: :some_id,
                message: Proc.new { GenerateCustomMessage },
                strict: SomeException
            },
            :format => {
                :with => proc { |a| Regexp.new(regexp_here) },
                :message =>  proc { |a| "why 'a' is nil but not my object ?" },
                strict: FormatIsInvalid
            }

在格式验证器中,我无法获得对象上下文(a)。我怎么能得到它?

1 个答案:

答案 0 :(得分:0)

我刚刚添加了自定义验证器

validates :address, :allow_nil => true, :allow_blank => true,
            uniqueness: {
                scope: :some_id,
                message: Proc.new { GenerateCustomMessage },
                strict: SomeException
            }

  validate :validate_address

  def validate_address
    regex = Regexp.new(regexp_here)
    unless address.blank?
      unless address =~ regex
        message = generate_dynamic_message
        errors.add(:address, message)
      end
    end
  end