[英]Adding a validation error with a before_save callback or custom validator?
[英]Adding an error message to a custom validator
我有一個自定義驗證器,我試圖輸出錯誤信息,但它失敗但無法這樣做。 有人可以告訴我,如果我在正確的地方這樣做。
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? 把問號和逗號橙色變成了問號
的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"}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.