我有一个自定义验证器,我尝试在失败时输出错误消息,但无法执行此操作。有人可以告诉我,如果我在正确的地方这样做。
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?转过问号和逗号橙色
答案 0 :(得分:17)
message
和if
参数应位于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"}