Ruby-on-rails Rails 3 的验证自定义消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5386785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
validation custom message for rails 3
提问by Prabesh Shrestha
Rails has introduced new way to validate attributes inside model. When I use
Rails 引入了验证模型内部属性的新方法。当我使用
validates :title, :presence => true
it works but when I try to add a custom message
它有效,但是当我尝试添加自定义消息时
validates :title, :presence => true,:message => "Story title is required"
an error is generated
产生错误
Unknown validator: 'message'
回答by Shiv
Try this
尝试这个
validates :title, presence: { message: "Story title is required" }
回答by Mateusgf
Actually, I did this in a better way. If you want to remove the field title from the message you should use this on your _form.htmk.erb view:
实际上,我以更好的方式做到了这一点。如果您想从消息中删除字段标题,您应该在 _form.htmk.erb 视图中使用它:
As you can see inside this view:
正如您在此视图中所见:
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
Replace it by:
替换为:
<ul>
<% @article.errors.each_with_index do |msg, i| %>
<li><%= msg[1] %></li>
<% end %>
</ul>
回答by stevenspiel
A custom message for a boolean with conditionals might be:
带有条件的布尔值的自定义消息可能是:
validates :foo, inclusion: { in: [true, false], message: "cannot be blank" }, if: :bar?
回答by Shyamkkhadka
You can use HUMANIZED_ATTRIBUTES of rails 3 . For example in above case, it will be like :
您可以使用 rails 3 的 HUMANIZED_ATTRIBUTES 。例如在上面的情况下,它会像:
HUMANIZED_ATTRIBUTES = {
:title => "story"
}
def self.human_attribute_name(attr, options={})
HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end
It will give you error message, replacing model attribute title with story.
它会给你错误信息,用故事替换模型属性标题。

