将错误消息添加到自定义验证器

时间:2012-04-26 14:23:20

标签: ruby-on-rails-3 rspec2 customvalidator custom-errors

我有一个自定义验证器,我尝试在失败时输出错误消息,但无法执行此操作。有人可以告诉我,如果我在正确的地方这样做。

class User < ActiveRecord::Base
  self.table_name = "user"

  attr_accessible :name, :ip, :printer_port, :scanner_port

  validates :name,        :presence => true,
                          :length => { :maximum => 75 },
                          :uniqueness => true                          

  validates :ip,          :length => { :maximum => 75 },
                          :allow_nil => true     

  validates :printer_port, :presence => true, :if => :has_association? 

  validates :scanner_port, :presence => true, :if => :has_association?          

  def has_association?
    ip != nil
  end
end

我有如下:

validates :printer_port, :presence => true, :message => "can't be blank", :if => :has_wfm_association?

但收到错误

Unknown validator: 'MessageValidator'

当我尝试将消息放在验证器的末尾时,逗号分隔has_association?转过问号和逗号橙色

1 个答案:

答案 0 :(得分:17)

messageif参数应位于presence的哈希值内:

validates :printer_port, :presence => {:message => "can't be blank", :if => :has_wfm_association?}

这是因为您可以在一行中加载多个验证:

validates :foo, :presence => true, :uniqueness => true

如果您尝试按照您的方式或if条件添加消息,Rails将不知道应用消息/条件的验证。因此,您需要设置每次验证的消息:

validates :foo, :presence => {:message => "must be present"},
                :uniqueness => {:message => "must be unique"}