【问题标题】:Adding an error message to a custom validator向自定义验证器添加错误消息
【发布时间】:2012-05-07 07:19:02
【问题描述】:

我有一个自定义验证器,我尝试在它失败但无法输出时输出错误消息。如果我在正确的地方这样做,有人可以告诉我。

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?把问号和逗号变成橙色

【问题讨论】:

    标签: ruby-on-rails-3 rspec2 customvalidator custom-errors


    【解决方案1】:

    messageif 参数应该在 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"}
    

    【讨论】:

    • 我不需要在现场包含真实的陈述吗?当我这样做的时候?和哈希的末尾一起运行并且都变成橙色。
    • 刚需要放空间,感谢您的帮助,非常感谢Dylan :)
    猜你喜欢
    • 2017-05-30
    • 2020-06-02
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多