126
142

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 5 years have passed since last update.

Rails エラーメッセージの表示

Last updated at Posted at 2018-10-04

#エラーメッセージとは
form_forとかで入力フォームを作った時に、
空のまま入力したりすると表示されるやつ。
フラッシュメッセージとは別物。

modelのバリデーションとセットで設定する感じ。

以下が完成図画像。
スクリーンショット 2018-10-04 22.37.42.png

#まずmodelにバリデーション

message.rb
class Message < ApplicationRecord
  belongs_to :user
  validates :title, presence: true, length: { maximum: 50 }
  validates :content, presence: true, length: { maximum: 140 }
end

titleカラムと。contentカラムは空白では登録できんぞ!ってこと。

#エラーメッセージのファイルの作成

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

errors.full_messages
全てのエラーメッセージを配列で取得します。
複数のメッセージが格納されていることもあるので、全て表示するには each でループで回しましょう。

いろんな入力フォームで使い回しできるように、パーシャルとして作成。

#フォーム(form_for)の中に、renderで挿入

messages/new.html.erb
<h2>メッセージの投稿</h2>

<%= form_for(@message) do |f|%>
<%= render 'layouts/error_messages', model: f.object %>
<div class="form-group">  
<%= f.label :title %>
<%= f.text_field :title %>
</div>

<div class="form-group">        
<%= f.label :content %>
<%= f.text_area :content %>
</div>

<%= f.submit "投稿する", class: "btn-primary" %>

<% end %>

<%= render 'layouts/error_messages', model: f.object %>この部分がエラーメッッセージに該当する部分です。

第二引数のmodel: f.objectはパーシャルに対して変数を渡しています。
modelという変数名で、f.objectという値を渡しています。
こうすることでパーシャルの汎用性が増します(他のフォームでも使える)。

参考
http://blog.yuhiisk.com/archive/2018/05/22/rails-display-error-message.html

126
142
2

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
126
142

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?