[RUBY] How to display error messages and success messages when registering as a user

Introduction

I created an article to organize my knowledge of how to display flash messages when signing up when creating a web service in Rails. The basis is the knowledge gained in the Rails tutorial.

Prerequisites

--Suppose you're in the process of creating a web service using Rails and you've already created a basic login feature yourself without using device. --Validation implemented

controller

python


def create
    @user = User.new(user_params) 
    if @user.save   #@Succeeded in saving user
      redirect_to @user  #Redirect to user details
    else
      render 'new'  #Return to new registration in case of failure
    end
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end

Error message when new registration fails

If the password is blank or otherwise validated during new registration, the screen returns to the new registration screen and an error message is displayed.

html:new.html.erb


 <%= form_for(@user) do |f| %>
      <%= render 'shared/error_messages' %>

      <%= f.label :name %>
      <%= f.text_field :name, class: 'form-control' %>

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

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

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

      <%= f.submit "Create my account", class: "btn btn-primary" %>
    <% end %>

In the above code, render is inserted in the form_for method and the error_messages file that is collected in the shared folder is brought. When inserting an error message etc., writing the code in a separate view does not change the result. However, it is customary in Rails to create a shared directory for partials used by multiple views, manage them there, and render them where needed. ___

Now let's take a look at the error_messages file.

html:_error_messages.html.erb


<% if @user.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      The form contains <%= pluralize(@user.errors.count, "error") %>.
    </div>
    <ul>
    <% @user.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

Various methods are used in this code. Let's look at each one.

<% if @user.errors.any? %>

This line uses the any? method for @ user.errors. The ___any? method returns true as a logical value, as it is read, if there is even one specified target. ___ Therefore, I've heard that the conditional expression of the if statement says "Is there something wrong with @user?" And if there is something wrong, the process below it will be activated and it will be inserted in the new.html.erb.

The form contains <%= pluralize(@user.errors.count, "error") %>.

Next is this code. This is the code that counts and displays the number of errors. There is a method called pluralize for words that seems difficult to see here, but it's not difficult at all. This is a method (English only) ___ that outputs the singular and plural forms separately according to the number counted arbitrarily. To give an example using a helper object

>> helper.pluralize(1, "error")
=> "1 error"
>> helper.pluralize(5, "error")
=> "5 errors"

In the above, when the ___pluralize method used for the helper object takes an integer value as the first argument, the English word of the second argument is output in plural form according to the integer value. ___ The great thing about this method is that it supports not only countable nouns but also uncountable nouns, so you can prevent it from becoming unnatural when you want to count and display something. Let's look at this code again.

The form contains <%= pluralize(@user.errors.count, "error") %>.

The first argument of the pluralize method is @ user.errors.count. Here, the count method counts the number of @ user.errors. Then, the singular or plural form is judged and output in the unit specified by the second argument. As a result, it will be written as The form contains 3 errors.

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

Then, the content of the error actually occurring in this each statement is displayed.

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

The errors.full_messages part of this statement checks the object for errors, and if so, prints out what's wrong using the error messages originally provided with Rails. To do. (There is also a way to output in Japanese, but I have not investigated it.) Then, put the output error message in a block called msg and output it with `<li> <% = msg%> </ li>`.

Success message when new registration is successful

Play with the controller a bit to see the success message.

users_controller.rb


def create
    @user = User.new(user_params)
    if @user.save
      flash[:success] = "Welcome to the Sample App!" #Specifying a message when it succeeds
      redirect_to @user
    else
      render 'new'
    end
  end

flash Only display success messages immediately after redirecting to the page. To do this, we use a special variable called flash. And the above controller is set to return "Welcome to the Sample App!" As a value when the key of the flash variable is success (Rails convention indicates success). Then use the each method in the flash variable in application.html.erb to display the success message. The code to add is as follows

html:applocation.html.erb


<!DOCTYPE html>
<html>
.
.
.
<% flash.each do |message_type, message| %>
  <div class="alert alert-<%= message_type %>"><%= message %></div>
<% end %>
.
.
.
</body>
</html>

The above code is a bit confusing and has a roundabout way of writing, so I'll simplify it later.

<% flash.each do |message_type, message| %>

At this point, there is a key called success and a value "Welcome to the Sample App!" In the flash variable, so take it out with the each method and put it in a block with a key called message_type and a block with a value called message. And it will be output below.

<div class="alert alert-<%= message_type %>"><%= message %></div>

class="alert alert-<%= message_type %>"There is a class used in bootstrap called, but if you put the key hereclass="alert alert-success"Next to it, bootstrap makes it cool.

Even this is displayed normally, but it is difficult to read, so use the content_tag method to make it one line.

html:application.html.erb


<!DOCTYPE html>
<html>
.
.
.
<% flash.each do |message_type, message| %>
     <%= content_tag(:div, message, class: "alert alert-#{message_type}") %>
<% end %>
.
.
.
</body>
</html>

This one is easier to read!

Impressions

Now that I understand the basic success and how to add error messages, I've been thinking about how to translate error messages into Japanese and how to use devise (I personally think that this is more important). I would like to understand well about w).

Recommended Posts

How to display error messages and success messages when registering as a user
[Rails] How to get success and error messages
When registering a new user, I got an error called ActiveRecord :: NotNullViolation and how to deal with it.
[Rails] How to display error messages individually
How to display error messages in Japanese
[Ruby on Rails] How to display error messages
[Rails] How to display error messages for comment function (for beginners)
How to read a file and treat it as standard input
What to do and how to install when an error occurs in DXRuby 1.4.7
I want to display an error message when registering in the database
[Rails] How to write when making a subquery
How to display a web page in Java
[Ruby on Rails] Add and delete tags and display (success / error) messages using ajax.
When defining a class, write formatTo as well as toString (how to use Formattable)
How to make a Vagrant Plugin that you learned when you forked and published vagrant-mutagen
[Personal application work memo] How to display a bar graph and a line graph in one graph
[Docker] How to update using a container on Heroku and how to deal with Migrate Error
How to run the SpringBoot app as a service
How to update devise user information without a password
What to do when a null byte error occurs
How to display a browser preview in VS Code
How to remove Ubuntu when dual booting Windows and Ubuntu
How to convert A to a and a to A using AND and OR in Java
[Kotlin] How to get IP address and user agent
[RSpec] How to test error messages set by Shoulda-Matchers
How to test including images when using ActiveStorage and Faker
How to request a CSV file as JSON with jMeter
How to resolve Missing Template error when implementing comment function
How to write and notes when migrating from VB to JAVA
How to display a graph in Ruby on Rails (LazyHighChart)
A validation error occurred when saving to the intermediate table.
link_to A blue dot appears when nesting! How to erase
How to develop and register a Sota app in Java
How to join a table without using DBFlute and sql
How to install GNOME as a desktop environment on CentOS 7
How to batch run JUnit and get coverage as well
How to create and launch a Dockerfile for Payara Micro
How to register as a customer with Square using Tomcat
How to leave a comment
[Java] How to display Wingdings
How to insert a video
How to create a method
[Swift] How to display when the quiz app answers correctly [Beginner]
I get a Ruby version error when I try to start Rails.
How to load a Spring upload file and view its contents
[jOOQ] How to CASE WHEN in the WHERE / AND / OR clause
What to do if you get a DISPLAY error in gym.render ()
How to output a list of strings in JSF as comma-separated strings
How to solve the unknown error when using slf4j in Java
[Reading impression] "How to learn Rails, how to write a book, and how to teach"
[Swift5] How to communicate from ViewController to Model and pass a value
[Rails 5] How to display the password change screen when using devise