rails 错误消息显示键,我只想要值 [英] rails error message displays key and I only want value

查看:40
本文介绍了rails 错误消息显示键,我只想要值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码来显示错误消息:

I have the following code to display error messages:

<% if @profile.errors.any? %>
    <% puts @profile.errors.full_messages.inspect.to_s %>
    <ul>
      <% @profile.errors.full_messages.each do |msg| %>
        <% puts 'errors ared' + msg.to_s %>
        <li><%= msg %></li>
      <% end %>
    </ul>
<% end %>

这是模型中的验证:

validates :title, presence: true, length: {maximum: 50, minimum: 5, too_long: "Title cannot be longer than %{count} characters", too_short:" must be at least %{count} characters."}

出于某种原因,这会打印带有错误和错误的属性名称.例如,如果我试图显示更新名为title"的表单字段的错误,错误消息将显示为:

For some reason, this prints both the name of the attribute with the error and the error. For example, if I am trying to display the error from updating a form field called "title", the error message will read:

Title Title cannot be longer than 50 characters

我想在整个网站上显示许多错误消息,但我不希望自动写入任何内容.怎么去掉开头的标题"二字?

I have many error messages I want to display throughout my site and I don't want anything being written automatically. How do I get rid of the word "Title" at the beginning?

推荐答案

full_messages 方法将属性名称添加到验证错误消息.以下是rails

full_messages method prepends attribute name to the validation error message. Following is the method implementation in rails

## Following code is extracted from Rails source code

def full_messages
      map { |attribute, message| full_message(attribute, message) }
end

def full_message(attribute, message)
      return message if attribute == :base
      attr_name = attribute.to_s.tr('.', '_').humanize
      attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
      I18n.t(:"errors.format", {
        default:  "%{attribute} %{message}",
        attribute: attr_name,
        message:   message
      })
 end

如果您看到 full_messages 方法,它会依次调用 full_messages,其中属性被添加到错误消息中.因此,如果您在 validation error message 中添加 attribute name 它肯定会被复制,这就是您的情况.

If you see the full_messages method it in turn calls full_messages wherein attribute gets prepended to the error message. So, if you add attribute name in the validation error message it is definitely going to be duplicated which is what is happening in your case.

简而言之,您不需要在验证消息中指定属性名称,因为 rails 已经在处理它了.

In nutshell, you don't need to specify attribute name in validation message, as rails is already taking care of it.

编辑

没有什么是不可能的.如果你愿意,你可以自定义如下

Nothing is impossible. If you want you could customize it as below

<% if @profile.errors.any? %>
    <ul>
      <% @profile.errors.messages.each do |attr, msg| %>
        <% msg.each do |val| %>
        <li><%= val %></li>
        <% end %>
      <% end %>
    </ul>
<% end %>

这篇关于rails 错误消息显示键,我只想要值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆