2012-03-23 4 views
10

私はuser.errorsを持っていますので、コントローラにエラーがあります。だから、私はそのフィールドに:user_loginのエラーがあります。どのように私はuser.errorsからのエラーメッセージは、そのフィールドの完全に得ることができますか?Rails 3 - 1つのフィールドで完全なエラーメッセージが表示される

私はそのようなこのフィールドのテキストだけ取得することができます。

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、error)} ' –

19

はまあ、私が知っているこの質問は、あなたが希望された非常に方法、full_messages_forを持っているようだ、明示的に1年半前に、Railsの3.xの掲載が、今の4.xをレールました。

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

関連する問題