3
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】エラーメッセージ とはなんだったのか

Last updated at Posted at 2020-09-15

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

###生成

>> 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;
}
3
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
3
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?