如何去掉出现在 Rails 模型错误消息周围的括号?

How do I get rid of brackets that are appearing around my Rails model error message?

我正在使用 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].join(', ')

这将如您所料显示单个错误,以及用逗号分隔的多个错误。

例如

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

变成

not an integer, not less than ten

['not an integer']

变成

not an integer

在 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 的文档。