[Ruby] [ERROR message display] Rails partial template that can be used anytime

1 minute read

##【goal】 Display error message

Screen capture 2020-06-23 18.49.15.mov.gif

##【merit】 ■ UX improvement ■ Improved understanding of partial templates

##【Development environment】 ■ Mac OS catalina ■ Ruby on Rails (5.2.4.2) ■ Virtual Box:6.1 ■ Vagrant: 2.2.7

##【Implementation】

Create application

*Touch is a command to create a file in the current directory

mac.terminal


$ rails new error_test
$ cd error_test
$ rails g scaffold Item name:string texte:text amount:integer
$ rails db:migrate
$ cd app/views/layouts
$ touch _error_messages.html.erb

Model addition

*Conditions for DB storage *Validation=Restriction on saving added

models/item.rb


class Item <ApplicationRecord
  validates :name, presence: true
  validates :text, presence: true
  validates :amount, presence: true
end

Added view

  • Partialized to improve mediocrity * By putting in “layputs/_error_messages.html.erb” It can be used for all models if validation is attached!!!!

layputs/_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 %>

※to add

Items/_form.html.erb


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

*** The above is not necessary when creating with scaffold ** Because the following code is described in each _form view (scaffold is super convenient)

/_form.....


<% if item.errors.any? %>
<div id="error_explanation">
  <h2><%= pluralize(item.errors.count, "error") %> prohibited this item from being saved:</h2>

  <ul>
    <% item.errors.full_messages.each do |message| %>
    <li><%= message %></li>
    <% end %>
  </ul>
</div>
<% end %>

*The original scaffold ![Screenshot 2020-06-23 18.46.33.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/620689/1b4368c6-4cb2-d49b-3155-(b0b5cf429a1c.png)

*Partial ![Screenshot 2020-06-23 18.47.29.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/620689/ac928fcf-1048-2149-d864-(a0a908a8d6b7.png)

that’s all. as you like! !! !!

[I want to read it together]

■ Regarding error messages https://qiita.com/ryuuuuuuuuuu/items/1a1e53d062bff774d88a

■ hidden_field https://qiita.com/tanaka-yu3/items/0d454c5ef80f8267f09d

■ Application creation https://qiita.com/tanaka-yu3/items/3fe1ed2852c6513d3583