I will write about how to display the error message. I will also briefly write about render, redirect_to, and flash, which are often used when outputting messages with Rails.
When the input value of the form is incorrect, the following error message is displayed.
login_controller.rb
@error_txt = '* There is an error in the input or it is not registered.'
render :new
Set the instance variable @error_txt to an error message and specify that render should display the template new.
new.html.slim
- if @error_txt
p.error
= @error_txt
On the template side, the existence of the value of @error_txt of the instance variable is checked, and @error_txt is displayed if it exists.
render is a method for specifying a template and displaying (rendering) it. It can be displayed without changing the screen.
Similar to render, redirect_to is a method to specify and display a page. While render displays the specified template without screen transition, The redirect_to method is a method for redirecting, which tells the browser to resubmit the request with a URL. In response to this directive, the browser sends another request to the server for the specified URL. Render is a good choice if you don't need to send the request again because it increases the interaction and processing between the browser and the server.
This time, I use render because I just want to display an error message for the input contents of the form and do not want to redirect.
If you look into message display in rails, you will find many articles about flash. flash is one of the functions using session and is a method for displaying a message on the screen. The message set by flash is saved in the session and is retained even if it is redirected, so the redirect_to method is often used together.
This time I'm using render, no redirects and no need to hold values in the session so I used instance variables instead of flash.
Recommended Posts