2012-03-23 6 views
10

मेरे पास user.errors है जो मेरे नियंत्रक में सभी त्रुटियां देता है। तो, मेरे पास फ़ील्ड :user_login है जिसमें इसकी त्रुटि है। मैं पूर्ण केवल उस क्षेत्र के लिए user.errors से त्रुटि संदेश कैसे प्राप्त कर सकता हूं?रेल 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' 

उत्तर

10

की तरह कुछ करने के लिए यहाँ full_message पर एक नजर है चाहते हैं:

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

थोड़ा वर्बोज़ लेकिन आप ऐसा करने में सक्षम हो सकते हैं कुछ की तरह:

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

वास्तव में इस तरह के और अधिक कुछ हो गया है | त्रुटि .map {| user.errors.full_message (: user_login, त्रुटि)} ' –

19

ठीक है, मैं इस सवाल का स्पष्ट रूप से साल पहले रेल 3.x, डेढ़ लिए तैनात किया गया था, लेकिन अब रेल 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

यहां प्रत्येक फ़ील्ड के लिए पहली त्रुटि प्रदर्शित करने के लिए कोड स्निपेट है। `resource.errors [:: USER_LOGIN]

<!-- 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?' –

संबंधित मुद्दे