Adding an error message to a custom validator

岁酱吖の 提交于 2019-12-08 15:58:30

问题


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? turned the question mark and comma orange


回答1:


The message and if parameters should be inside a hash for 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. So instead, you need to set the message per-validation:

validates :foo, :presence => {:message => "must be present"},
                :uniqueness => {:message => "must be unique"}


来源:https://stackoverflow.com/questions/10335438/adding-an-error-message-to-a-custom-validator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!