Rails 3 - 获取一个字段的完整错误消息

Posted

技术标签:

【中文标题】Rails 3 - 获取一个字段的完整错误消息【英文标题】:Rails 3 - get full error message for one field 【发布时间】:2012-04-07 22:18:42 【问题描述】:

我有user.errors,它给出了我的控制器中的所有错误。所以,我有字段:user_login,它有错误。我如何才能从user.errors 获得完整 错误消息,仅针对该字段?

我可以像这样得到这个字段的文本:

user.errors[:user_login] # Gives that 'can't be empty'

但我真的很想做这样的事情

user.errors.get_full_message_for_field[:user_login] # 'Your login can't be empty'

【问题讨论】:

Quv's answer below 现在似乎是最好的选择。可能值得切换接受的答案@ExiRe? 【参考方案1】:

嗯,我知道这个问题是在一年半前针对 Rails 3.x 明确发布的,但现在 Rails 4.x 似乎拥有您想要的方法,full_messages_for

user.errors.full_messages_for(:user_login) #=> return an array
# if you want the first message of all the errors a specific attribute gets,
user.errors.full_messages_for(:user_login).first
# or
user.errors.full_messages_for(:user_login)[0]

它比以前使用的user.errors.full_message(:user_login, user.errors[:user_login].first) 更简洁。

【讨论】:

【参考方案2】:

在这里查看full_message

http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-full_message

有点冗长,但您可以执行以下操作:

user.errors.full_message(:user_login, user.errors[:user_login])

【讨论】:

实际上必须更像这样:resource.errors[:user_login].map |error| user.errors.full_message(:user_login, error) 【参考方案3】:
We can get the error message of particular field by using

<%= resource.errors.full_messages_for(:email).join("") %>

output : Email cant be blank

If you want to check the particular field has error or not then check it by using

resource.errors.include?(:email)

output : true/false

【讨论】:

很适合使用full_messages_for。顺便检查一下特定字段是否有错误,我们也可以使用它resource.errors[:field].any?【参考方案4】:

这里是代码 sn-p,用于仅显示每个字段的第一个错误。

<!-- Display only first error for each field --->
<% entity.attributes.keys.each do |key| %>
    <% if entity.errors.full_messages_for(key.to_sym).length > 0 %>
        <li><%= entity.errors.full_messages_for(key.to_sym).first %></li>
    <% end %>
<% end %>   

【讨论】:

以上是关于Rails 3 - 获取一个字段的完整错误消息的主要内容,如果未能解决你的问题,请参考以下文章

Rails - 从模型中获取不是验证错误的错误消息

设计为重复的用户名创建错误消息

使用 Rails 完全自定义验证错误消息

如何在 Rails 验证错误中突出显示字段

如何在Rails 5中更改设计中的验证错误消息

在Michael Hartl的Ruby on Rails教程中获取错误消息:MicropostsController中的NoMethodError #create,如何避免收到此消息?