Ruby-on-rails 从验证错误消息中删除字段名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5375407/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:43:48  来源:igfitidea点击:

removing field name from validation error message

ruby-on-railsruby-on-rails-3

提问by hakaooa

in rails 3 i don't want to show field names in error messages. Anyone know how to do that ?

在 Rails 3 中,我不想在错误消息中显示字段名称。有谁知道怎么做?

validates_presence_of :title, :message => "no title"

it shows

表明

Title no title 

i want

我想要

no title

回答by Erick Eduardo Garcia

In your form view change your current code

在您的表单视图中更改您当前的代码

      <%@object.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>

With this

有了这个

      <%@object.errors.messages.values.each do |msg| %>
        <%msg.each do  |m| %>
          <li><%= m %></li>
        <%end %>
      <% end %>

回答by Richard Peck

This worked for us (Rails 4):

这对我们有用(Rails 4):

<% resource.errors.each do |attr,msg| %>
    <li><%= msg %></li>
<% end %>

回答by Adam Cooper

This worked for me in Rails 4 (haml):

这在 Rails 4 (haml) 中对我有用:

%ul
  - @some_object.errors.messages.each do |message|
    %li= message[1][0]

回答by Rodrigo Casara

module ActiveModel
  class Errors
    def full_messages
      map { |attribute, message|
        message
      }
    end
  end
end

See also: Change displayed column name in rails

另请参阅:更改 rails 中显示的列名

回答by Abhi

You can use the following Gem

您可以使用以下 Gem

https://github.com/jeremydurham/custom-err-msg

https://github.com/jeremydurham/custom-err-msg

You can use a '^' character at the start of the message value. And it will only show the characters after this.

您可以在消息值的开头使用“^”字符。它只会显示此后的字符。

 validates_presence_of :title, :message => "^no title"

You can use the following Gem also

您也可以使用以下 Gem

http://www.rubydoc.info/gems/dynamic_form/1.1.4

http://www.rubydoc.info/gems/dynamic_form/1.1.4

回答by code0100fun

If you change the label of the element it will effect the error message label. So if you change it to a blank string it will render just the message:

如果您更改元素的标签,它将影响错误消息标签。因此,如果将其更改为空白字符串,它将仅呈现消息:

-# reviews/_form.html.haml
= form_for review do |form|
  = form.label :rating, (review.errors[:rating] ? "" : "Rate this Item" )