简体   繁体   English

Ruby on Rails:控制ActiveRecord中错误消息的布局

[英]Ruby on Rails: controlling the layout of an error message in ActiveRecord

My error messages in Rails look like the following: 我在Rails中的错误消息如下所示:

"Email Your email is invalid." “电子邮件您的电子邮件无效。”

Why is the name of the field prefixed within the string itself? 为什么字段的名称在字符串本身前面加上前缀? It makes the error messages look awfully odd. 它使错误消息看起来非常奇怪。

Is there anyway to circumvent this behavior so that I can just see "Your email is invalid." 无论如何都要规避这种行为,以便我能看到“你的电子邮件无效”。

The documentation for generate_full_message might be of use: generate_full_message的文档可能有用:

The default full_message format for any locale is " {{attribute}} {{message}} ". 任何区域设置的默认full_message格式为“ {{attribute}} {{message}} ”。 One can specify locale specific default full_message format by storing it as a translation for the key: " activerecord.errors.full_messages.format ". 可以通过将其存储为密钥的转换来指定特定于语言环境的默认full_message格式:“ activerecord.errors.full_messages.format ”。

Additionally one can specify a validation specific error message format by storing a translation for: " activerecord.errors.full_messages.[message_key] ". 另外,可以通过存储以下内容的转换来指定验证特定的错误消息格式:“ activerecord.errors.full_messages.[message_key] ”。 Eg the full_message format for any validation that uses :blank as a message key (such as validates_presence_of) can be stored to: " activerecord.errors.full_messages.blank ". 例如,任何使用的验证的full_message格式:空白作为消息密钥(例如validates_presence_of)可以存储到:“ activerecord.errors.full_messages.blank ”。

Because the message key used by a validation can be overwritten on the validates_* class macro level one can customize the full_message format for any particular validation: 由于验证使用的消息密钥可以在validates_ *类宏级别上覆盖,因此可以为任何特定验证自定义full_message格式:

# app/models/article.rb
class Article < ActiveRecord::Base
  validates_presence_of :title, :message => :"title.blank"
end

# config/locales/en.yml
en:
  activerecord:
    errors:
      full_messages:
        title:
          blank: This title is screwed!

In your case, since you're using the default {{attribute}} {{message}} format, you're getting "Email" for the attribute and "Your email is invalid" as the message. 在您的情况下,由于您使用的是默认的{{attribute}} {{message}}格式,因此您将获得该属性的“电子邮件”和“您的电子邮件无效”作为邮件。 You could change the :message argument to "is not a valid format" and you should get "Email is not a valid format". 您可以将:message参数更改为“不是有效格式”,您应该得到“电子邮件不是有效格式”。 That's the quick fix. 这是快速修复。 If you want to fully customize it you can use the locale method above. 如果要完全自定义它,可以使用上面的语言环境方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM