[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 ( ■ Virtual Box:6.1 ■ Vagrant: 2.2.7


Create application

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


$ 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


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

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!!!!


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

※to add


<%= 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)


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

    <% item.errors.full_messages.each do |message| %>
    <li><%= message %></li>
    <% end %>
<% 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