9

我有一个自定义验证器,当它失败但无法输出时,我试图输出一条错误消息。有人可以告诉我我是否在正确的地方这样做。

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? 把问号和逗号变成橙色

4

1 回答 1

17

和参数应该在散列message中:ifpresence

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"}
于 2012-04-26T14:46:33.790 回答