如果我想在所有验证上获得相同的错误消息,我该如何编码?
我有三个标准,如presence
, uniqueness
和length
。
我想要相同的错误信息。
但是我的代码只有在匹配长度错误时才能工作。
我如何申请所有(其他两个)?
validates :title,
:presence => true,
:uniqueness => true,
:length => { :maximum => 100, :message => "Must be unique, and has to be less than 100 characters"}
我相信有一种方法可以使用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个字符"。你可能会选择其中一个,并保持一致。
可以通过验证
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"}