Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - get full error message for one field

I have user.errors which gives all errors in my controller. So, i have the field :user_login which has its error(s). How can i get full error messages from user.errors ONLY for that field?

I can get just text of this field like that:

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

But i really want to do something like that

user.errors.get_full_message_for_field[:user_login] # 'Your login can't be empty'
like image 780
ExiRe Avatar asked Mar 23 '12 10:03

ExiRe


1 Answers

Well, I know this question was explicitly posted for Rails 3.x, one and a half years ago, but now Rails 4.x seems to have the very method you were wishing, 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]

It's less verbose than the previously used user.errors.full_message(:user_login, user.errors[:user_login].first).

like image 117
Quv Avatar answered Nov 06 '22 05:11

Quv