如果我想在所有验证中使用相同的错误消息,我该如何编码?
我有3个标准,例如presence
,uniqueness
和length
。
我想要相同的错误信息
但是我的代码只有在与长度误差匹配时才有效
我如何申请所有(另外两个)?
validates :title,
:presence => true,
:uniqueness => true,
:length => { :maximum => 100, :message => "Must be unique, and has to be less than 100 characters"}
答案 0 :(得分:1)
我确信有一种方法可以使用validates
执行此操作,但如果我遇到此问题,我可能只是编写自定义验证:
validate :title_format
def title_format
if title.blank? || title.length > 100 || Post.where(:title => title).exists?
errors.add(:title, "Must be unique and less than 100 characters")
end
end
(当然,将Post替换为您的实际型号名称。)
顺便提一下,您的消息显示“少于100个字符”,但您实际上正在验证“小于或等于100个字符”。你可能想要选择其中一个并保持一致。
答案 1 :(得分:1)
可以使用验证
来完成validates :title,
:presence => {:message => "Must be unique, and has to be less than 100 characters" },
:uniqueness => {:message => "Must be unique, and has to be less than 100 characters"},
:length => { :maximum => 100, :message => "Must be unique, and has to be less than 100 characters"}