2012-03-23 41 views
10

我有user.errors,它给出了我的控制器中的所有错误。所以,我有字段:user_login,它有错误。我如何才能获得全部来自user.errors的错误消息仅适用于该字段?Rails 3 - 获取一个字段的完整错误消息

我能得到这个领域的只是文字那样:

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' 

回答

19

好了,我知道这个问题被明确公布为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)更简洁。

0

以下是仅显示每个字段的第一个错误的代码片段。

<!-- 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 %> 
1
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 
+0

使用'full_messages_for'很好。顺便检查一下特定的字段是否有错误,我们可以使用'resource.errors [:field] .any?' – 2016-02-26 04:33:35