[RUBY] Implementation of flash messages

What is a flash message?

This is a message that is displayed so that the user can understand the result of the processing when the processing is performed based on the input of the user. For example, it is used for account registration and account information update processing.

It's not that difficult to implement, so make sure you understand how it works.

Implementation method

In this article, we will implement the user registration function in the action controller. The registration form is a simple form like the image below.

image.png

By pressing the register button, the create action, which is a newly registered action, is executed. (Flash message written)

app/controllers/users_controller.rb


class UsersController < ApplicationController
 
  def create
    @user = User.new(user_params)

    if @user.save
      flash[:success] = 'User registration is complete'
      redirect_to login_path 
    else
      flash.now[:danger] = 'User registration failed'
      render :new 
    end
  end

  private

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

The first line of the create action is passed what you typed in the instance variable @ user.

@user = User.new(user_params)

As a side note, user_params is defined in the line below as a private method.

private

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

This is __strong parameter __, which simply means that no one is allowed to retrieve anything other than the value enclosed in () of ** permit **. This is a security measure that prevents a malicious user from getting information other than what the user has entered, which is essential knowledge in Rails.

The instance variable @ user is subjected to the save method in a conditional branch.

if @user.save

This save method determines if the information required for user registration has been entered correctly and returns true if the information is correct. On the contrary, if the input field is blank or the confirmation password is different from the entered password, false is returned.

It's finally time to meet the flash message, which is the topic of this article. If the information is entered correctly, the registration will be completed.

flash[:success] = 'User registration is complete'
redirect_to login_path 

The character is stored in flash [: success], and the message "User registration is completed" is displayed in the redirect destination login_path. That's really it!

By the way, the above sentence can be written in one sentence. This is preferred because the code ** emphasizes the speed at which the programmer understands the code **. (But please note that you can't do this without implementing the add_flash_types mentioned in the last section of this article ...)

redirect_to login_path, flash: 'User registration is complete'

Conversely, if the information is not entered correctly, else and beyond will be executed.

flash.now[:danger] = 'User registration failed'
render :new 

A message will be displayed on the new registration page, which is the render destination.

How to use flash.now and flash properly

If you go first from the conclusion,

** Flash on success (redirect) Flash.now ** in case of failure (render)

To explain in detail, basically, the if statement is used for new registration and editing functions, redirect_to for true, and render for false.

There is a big difference between redirect_to and render.

** redirect_to ・ ・ ・ Screen transition via action render ・ ・ ・ Screen transition without going through action **

And there is a difference between flash and flash.now.

** flash ・ ・ ・ It does not disappear via the first action and is displayed until the next action. flash.now ・ ・ ・ It disappears when you move to the next action. ** **

Since render only displays the page without going through the action, if you use flash ** it will take two actions before the display disappears **. In other words, in this example, the correct information is entered and the message "User registration is complete" is displayed on the login page. The next page after login is also energetic and "User registration is complete." "I did" is displayed.

On the contrary, redireict_to goes through the following actions, so it will not even be displayed in Flash.now, and as a result you will never see the message.

It may have been a little confusing, but in summary ** Use flash for redirect_to and flash.now for render! ** **

Change message color with add_flash_types

Finally, I will touch on add_flash_types as a supplement. This will allow you to load the styles defined in Bootstrap.

It's easy to implement, just add the settings to application_contrller.rb, which is provided by default in rails.

app/controllers/application_controller.rb


class ApplicationController < ActionController::Base
  add_flash_types :success, :info, :warning, :danger
end

This allows you to change the color of the message according to the type of message. (success is a soft color that feels like success, danger is a piercing color that feels like when it fails (laughs))

Also, as described later, the redirect_to for displaying the successful flash message can be described in one line.

redirect_to login_path, flash: 'User registration is complete'

That's all about flash messages!

Recommended Posts

Implementation of flash messages
Implementation of GKAccessPoint
Implementation of search function
Applied implementation of chat-space
Implementation of pagination function
Explanation of Ruby on rails for beginners ⑦ ~ Flash implementation ~
Japanese localization of error messages
Rails implementation of ajax removal
[Swift] Simple implementation of UIImageView
Japanese localization of error messages
Implementation of sequential search function
form_with local and flash messages
[Swift] Implementation of ultra-simple billing
Implementation of like function (Ajax)
[Rails 6] Implementation of search function
Implementation of image preview function
[Java] Implementation of Faistel Network
Implementation of XLPagerTabStrip with TabBarController
[Rails] Implementation of category function
Display Flash messages in Rails
Implementation of category pull-down function
Implementation of unit test code
Implementation of gzip in java
[Rails] Implementation of tutorial function
[Rails] Implementation of like function
Implementation of tri-tree in Java
Implementation of HashMap in kotlin
[Rails] Implementation of user logic deletion
[Rails] Implementation of CSV import function
[Rails] Asynchronous implementation of like function
[Rails] How to use flash messages
[Rails] Implementation of image preview function
Implementation of ls command in Ruby
Easy implementation of Android file browsing
[Rails] About implementation of like function
[Rails] Implementation of user withdrawal function
[Rails] Implementation of CSV export function
Validation of log messages using mockito
Implementation of asynchronous processing in Tomcat
Implementation of validation using regular expressions
Japanese localization of error messages (rails)
[Rails] Implementation of many-to-many category functions
Animated display of Swift error messages
Default implementation of Object.equals () and Object.hashCode ()
Implementation of like function in Java
[Android] Implementation of side-scrolling ListView using RecyclerView
Implementation of clone method for Java Record
Implementation of DBlayer in Java (RDB, MySQL)
Whereabouts of JAXB Reference implementation and DatatypeConverterImpl
Implementation of user authentication function using devise (2)
[Swift 5] Implementation of membership registration with Firebase
Implementation of multi-tenant asynchronous processing in Tomcat
Implementation of user authentication function using devise (1)
Rails [For beginners] Implementation of comment function
[Rails 6] Implementation of SNS (Twitter) sharing function
Implementation of tabs using TabLayout and ViewPager
Implementation of user authentication function using devise (3)
[Vue.js] Implementation of menu function Implementation version rails6
[Ruby on rails] Implementation of like function
[Rails] Implementation of validation that maintains uniqueness
[Vue.js] Implementation of menu function Vue.js introduction rails6