这是另一种方式:
如果您使用此模板:
<% if @thing.errors.any? %>
<ul>
<% @thing.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
您可以像这样编写自己的自定义消息:
class Thing < ActiveRecord::Base
validate :custom_validation_method_with_message
def custom_validation_method_with_message
if some_model_attribute.blank?
errors.add(:_, "My custom message")
end
end
这样,因为有下划线,完整的消息变成了“我的自定义消息”,但是开头的多余空格是不明显的。如果您真的不希望开头有多余的空间,只需添加 .lstrip 方法即可。
<% if @thing.errors.any? %>
<ul>
<% @thing.errors.full_messages.each do |message| %>
<li><%= message.lstrip %></li>
<% end %>
</ul>
<% end %>
String.lstrip 方法将消除由 ':_' 创建的额外空间,并保持任何其他错误消息不变。
或者更好的是,使用自定义消息的第一个单词作为键:
def custom_validation_method_with_message
if some_model_attribute.blank?
errors.add(:my, "custom message")
end
end
现在完整的消息将是“我的自定义消息”,没有多余的空间。
如果您希望完整消息以“URL 不能为空白”之类的大写单词开头,则无法完成。而是尝试添加一些其他单词作为键:
def custom_validation_method_with_message
if some_model_attribute.blank?
errors.add(:the, "URL can't be blank")
end
end
现在完整的消息将是“URL 不能为空”