Подтвердить что ты не робот

Rails 3 - получить полное сообщение об ошибке для одного поля

У меня есть 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'
4b9b3361

Ответ 2

Ну, я знаю, что этот вопрос был явно опубликован для 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).

Ответ 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

Ответ 4

Вот фрагмент кода для отображения только первой ошибки для каждого поля.

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