Jay*_*Jay 9 customvalidator custom-errors rspec2 ruby-on-rails-3
我有一个自定义验证器,我试图输出错误信息,但它失败但无法这样做.有人可以告诉我,如果我在正确的地方这样做.
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
Run Code Online (Sandbox Code Playgroud)
我有如下:
validates :printer_port, :presence => true, :message => "can't be blank", :if => :has_wfm_association?
Run Code Online (Sandbox Code Playgroud)
但是收到了一个错误
Unknown validator: 'MessageValidator'
Run Code Online (Sandbox Code Playgroud)
当我试图将消息放在验证器的末尾时,逗号分隔has_association?把问号和逗号橙色变成了问号
Dyl*_*kow 17
在message
和if
参数应该是一个散列里面presence
:
validates :printer_port, :presence => {:message => "can't be blank", :if => :has_wfm_association?}
Run Code Online (Sandbox Code Playgroud)
这是因为您可以在一行中加载多个验证:
validates :foo, :presence => true, :uniqueness => true
Run Code Online (Sandbox Code Playgroud)
如果您尝试按照您的方式或if
条件添加消息,Rails将不知道应用消息/条件的验证.因此,您需要设置每次验证的消息:
validates :foo, :presence => {:message => "must be present"},
:uniqueness => {:message => "must be unique"}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4770 次 |
最近记录: |