[英]Adding an error message to a custom validator
I have a custom validator and I am trying to output an error message when it fails but have been unable to do so. 我有一个自定义验证器,我试图输出错误信息,但它失败但无法这样做。 Could someone please tell me if I am doing this in the correct place.
有人可以告诉我,如果我在正确的地方这样做。
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
I had it as follows: 我有如下:
validates :printer_port, :presence => true, :message => "can't be blank", :if => :has_wfm_association?
But was receiving an error 但是收到了一个错误
Unknown validator: 'MessageValidator'
And when I tried to put the message at the end of the validator the comma seperating the has_association? 当我试图将消息放在验证器的末尾时,逗号分隔has_association? turned the question mark and comma orange
把问号和逗号橙色变成了问号
The message
and if
parameters should be inside a hash for presence
: 的
message
和if
参数应该是散列内部presence
:
validates :printer_port, :presence => {:message => "can't be blank", :if => :has_wfm_association?}
This is because you can load multiple validations in a single line: 这是因为您可以在一行中加载多个验证:
validates :foo, :presence => true, :uniqueness => true
If you tried to add a message to that the way you did, or an if
condition, Rails wouldn't know what validation to apply the message/conditional to. 如果您尝试按照您的方式或
if
条件添加消息,Rails将不知道应用消息/条件的验证。 So instead, you need to set the message per-validation: 因此,您需要设置每次验证的消息:
validates :foo, :presence => {:message => "must be present"},
:uniqueness => {:message => "must be unique"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.