2012-03-23 6 views
10

Mam user.errors, który daje wszystkie błędy w moim kontrolerze. Tak więc mam pole :user_login, które ma swój błąd (s). Jak mogę uzyskać pełne komunikaty o błędach TYLKO dla tego pola TYLKO dla ?Szyny 3 - otrzymujesz pełny komunikat o błędzie dla jednego pola

mogę dostać tylko tekst tej dziedzinie tak:

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

Ale naprawdę chcę zrobić coś takiego

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

Odpowiedz

19

Wiem, kwestia ta została wyraźnie pisał dla Rails 3.x, półtora roku temu, ale teraz Szyny 4.x wydaje się mieć bardzo metodę ty życzyć, 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] 

Jest mniej gadatliwy niż poprzednio używany user.errors.full_message(:user_login, user.errors[:user_login].first).

0

Oto fragment kodu służący do wyświetlania tylko pierwszego błędu dla każdego pola.

<!-- 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

dobry do używania' full_messages_for'. Przy okazji sprawdzając, czy konkretne pole zawiera błędy/nie, możemy użyć tego również 'resource.errors [: field] .any?' –