2017-01-03 3 views
1

は、私がRailsモデルのエラーメッセージの周囲に表示されている角括弧を取り除くにはどうすればよいですか?私のフィールドの1つが有効でない場合は、私は私のモデルではRailsの5を使用してい

errors.add(:my_field, 'The field is not in the correct format') 

、その後、私の見解では、私はそうのようなエラーが表示さ...エラーを設定します。..エラーが表示されたら。

<% if [email protected][:my_field].empty? %><span class="profileError"> <%= @user.errors[:my_field] %></span><% end %> 

、それは

["The field is not in the correct format"] 

として表示されますどのように私は、エラーを回避表示され、それらの括弧を取り除くのですか?これは本当にシンプルな問題のように思えますが、私はそれらのものがそこにどのように忍び寄っているのか分かりません。

+0

この '@ user.errors [:my_field]'を '@user.errors [:my_field] .first'に変更してください – sahil

答えて

2

@user.errors[:my_field]は、エラーメッセージの配列です。これは、あなたが期待するように、単一のエラーを表示し、カンマで区切っmulitpleエラーます

@user.errors[:my_field].join(', ') 

...あなたが行うことができ、すべてのエラーを表示するには

['not an integer', 'not less than ten'] 

がレールに

not an integer 
1

なる

not an integer, not less than ten 

['not an integer'] 

なる任意の与えられた属性のエラーは、属性が複数の検証に失敗することができるので、アレイです。

通常は、@user.errors.full_messagesを使用して、しかし、すべてのエラーメッセージ反復:所望の出力はあなたが何であるかに応じて、

<% @user.errors[:my_field].each do |msg| %> 
    <span class="profileError"><%= msg %></span> 
<% end if @user.errors[:my_field].any? %> 

:あなたが特定のキーものの繰り返すことができますあなたのケースでは

<% if @user.errors.any? %> 
<ul> 
    <%= @user.errors.full_messages.each do |m| %> 
    <li><%= m %></li> 
    <% end %> 
</ul> 
<% end %> 

full_messages_for(:my_field)も使用できます。より多くの例については、ActiveModel::Errorsのドキュメントを参照してください。

関連する問題