0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

データベースに登録するときにエラーメッセージを表示させたい

Posted at

はじめに

 テストコードを書いていて、エラーメッセージを表示させるようにしたときに、わからなかったことなので、記録として残しておく。

エラーメッセージの表示方法

viewディレクトリに

_error_messages.html.erb
<% if model.errors.any? %>
  <div id="error_explanation" class="alert alert-danger">
    <ul>
      <% model.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
    </ul>
  </div>
<% end %>

を作成し、renderメソッドで呼び出すようにする。
1行目のmodelは、今回データベースに何かを登録する場面を想定しているため。

呼び出す側のコード

<%= render 'error_messages', model: f.object %>

ファイルの位置によって、shared/error_messagesのように指定してあげる必要がある。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?