【问题标题】:rails error message displays key and I only want valuerails 错误消息显示键,我只想要值
【发布时间】:2014-02-25 22:16:28
【问题描述】:

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

<% 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”的表单字段的错误,错误消息将显示为:

Title Title cannot be longer than 50 characters

我有许多错误消息要在我的网站上显示,并且我不希望自动编写任何内容。怎么去掉开头的“Title”二字?

【问题讨论】:

  • too_long: "Title cannot be longer... 中删除“标题”?似乎它会自动添加它。
  • 是的,这将解决这个问题,但这只是一个例子。我想知道如何解决将属性附加到错误消息的rails问题。
  • 似乎在 Rails 3 中使用语言环境自定义错误消息:stackoverflow.com/questions/808547/… 我不知道 Rails 4 中是否有更好的方法。
  • @Philip7899 我为您的代码编写了一个自定义实现。请在编辑部分查看我的更新答案

标签: ruby-on-rails ruby validation ruby-on-rails-4


【解决方案1】:

full_messages 方法将attribute name 前置到validation error message。 以下是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,它肯定会被复制,这就是您的情况。

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

编辑

没有什么是不可能的。如果你愿意,你可以定制它如下

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

【讨论】:

  • @Philip7899 很高兴为您提供帮助。我也应该投赞成票吗? :)
【解决方案2】:

我会像这样使用message。我认为这可以解决您的问题。

validates :title, presence: true, length: { maximum: 50, minimum: 5, message: 'Title should be between 5 and 50 characters' }

然后在视图中

  <% @profile.errors.each do |attr, msg| %>
    <% puts 'errors ared' + msg.to_s %>
    <li><%= msg %></li>
  <% end %>

关键是使用errors 而不是full_messages,然后将每个错误拆分为attrmsg,并仅获取message 或随意编写消息。

【讨论】:

    猜你喜欢
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    相关资源
    最近更新 更多