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.

【Rails】エラーメッセージ表示

Posted at

# 目標

  • エラーメッセージを表示させる
    スクリーンショット 2021-08-29 20.36.55.png

  • ユーザーの登録や投稿がなんで失敗したか知らせてくれるメッセージ

実装

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

app/views/layouts/_error_messeages.html.erb
<% if model.errors.any? %>
  <div id="error_explanation" class="alert alert-warning">
    <ul class="mb-0">
      <% model.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
    </ul>
  </div>
<% end %>

バリデーション

新規登録の際の制限を記述。
ここに記述した制限に引っかかった場合にエラーメッセージで表示される。

app/models/user.rb
class User < ApplicationRecord
  before_save { email.downcase! }
  validates :name, presence: true, length: { maximum: 50 }
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i },
                    uniqueness: { case_sensitive: false }
  has_secure_password

新規登録フォームにパーシャルrenderでエラーメッセージファイルを記述する。
<%= render 'layouts/error_messages', model: f.object %>

app/views/users/new.html.erb

  <h1>Sign up</h1>

    <%= form_with(model: @user) do |f| %>
     <%= render 'layouts/error_messages', model: f.object %>
    
      <div>
        <%= f.label :name, 'Name' %>
        <%= f.text_field :name, class: 'form-control' %>
      </div>

      <div>
        <%= f.label :email, 'Email' %>
        <%= f.email_field :email, class: 'form-control' %>
      </div>

      <div>
        <%= f.label :password, 'Password' %>
        <%= f.password_field :password, class: 'form-control' %>
      </div>

      <div>
        <%= f.label :password_confirmation, 'Confirmation' %>
        <%= f.password_field :password_confirmation, class: 'form-control' %>
      </div>

      <%= f.submit 'Sign up', class: 'btn btn-primary' %>
    <% end %>

これでエラーメッセージが表示されます、他のフォームも同様の方法で大丈夫です。

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?