【问题标题】:How do I get rid of brackets that are appearing around my Rails model error message?如何摆脱出现在 Rails 模型错误消息周围的括号?
【发布时间】:2017-05-17 16:55:50
【问题描述】:

我正在使用 Rails 5。在我的模型中,如果我的某个字段无效,我会设置一个错误...

errors.add(:my_field, 'The field is not in the correct format')

然后在我看来,我会像这样显示错误...

<% if !@user.errors[:my_field].empty? %><span class="profileError"> <%= @user.errors[:my_field] %></span><% end %>  

显示错误时,显示为

["The field is not in the correct format"]

如何去掉出现在错误周围的括号?这似乎是一个非常简单的问题,但我不知道这些东西是如何潜入其中的。

【问题讨论】:

  • 把这个@user.errors[:my_field]改成@user.errors[:my_field].first

标签: ruby-on-rails validation model ruby-on-rails-5


【解决方案1】:

@user.errors[:my_field] 是一个错误消息数组。

要显示所有错误,您可以这样做...

@user.errors[:my_field].join(', ')

这将按您的预期显示单个错误,并以逗号分隔多个错误。

例如

['not an integer', 'not less than ten']

变成

not an integer, not less than ten

['not an integer']

变成

not an integer

【讨论】:

    【解决方案2】:

    在 Rails 中,任何给定属性的错误都是一个数组,因为一个属性可能会失败多次验证。

    通常您使用@user.errors.full_messages,然后遍历所有错误消息:

    <% if @user.errors.any? %>
    <ul>
      <%= @user.errors.full_messages.each do |m| %>
      <li><%= m %></li> 
      <% end %>
    </ul>
    <% end %>
    

    在您的情况下,您可以遍历特定的键:

    <% @user.errors[:my_field].each do |msg| %>
      <span class="profileError"><%= msg %></span>
    <% end if @user.errors[:my_field].any? %>
    

    根据所需的输出,您也可以使用full_messages_for(:my_field)。有关更多示例,请参阅ActiveModel::Errors 的文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 2016-07-25
      相关资源
      最近更新 更多