Help us understand the problem. What is going on with this article?

【rails】エラーメッセージ とはなんだったのか

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

生成

>> user = User.new

>> user.save    #エラーメッセージ生成
=> false

>> user.error.full_messages  
=> [Failed"", "invalid"]

オブジェクトを保存する際、falseが返ってきた瞬間に配列の要素としてエラーメッセージが生成される。

表示

erb
<% @user.errors.full_messages.each do |msg| %>
  <%= msg %>
<% end %>

配列の要素をeach文で、それぞれ取り出し、表示させることができる

エラー時にのみ出現するClass属性

class="field_with_errors"
自動でエラー箇所の入力部品を囲んでくれる。

実装

パーシャルを使いつつ、どんなオブジェクトでも対応できるように実装させている。

shared/_error_messages.html.erb
<% if object.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger alert-form-extend" role="alert">
      <%= object.errors.count %>個のエラーがある
    </div>
    <ul>
      <% @user.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
    </ul>
  </div>
<% end %>
users/new.html.erb
<%= form_with(model: @user, url: users_path, local: true) do |form| %>
  <%= render 'shared/error_messages', object: form.object %>
users_controller.rb
def create
  @user = User.new(user_params)
  if @user.save
    ~~
  else
    render 'new'
  end
end
application.scss
#error_explanation {
  color: red;
  ul {
    color: red;
    padding-bottom: 0;
  }
}

.field_with_errors .form-control { 
  border-color: red;
}
prum
エンジニアが日本で一番成長できる環境を作り続ける
https://www.prum.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした