The title is long. Here is a summary of friendly forwarding.
It's a kind of process like "The page you requested, the page after login, but you haven't logged in yet. I'll guide you to the page you wanted to go to after logging in." Kind design that you often see. It's fine.
The general flow is as follows.
Prepare a method (1) for temporarily saving the request and a method (3) for returning to the temporarily saved URL. This time, in
sessions_helper.rb, write as follows.
# 1.Temporarily save the requested URL def store_location session[:forwarding_url] = request.original_url if request.get? end # 3.Revert to the requested URL def redirect_back_or(default) redirect_to(session[:forwarding_url] || default) session.delete(:forwarding_url) end
Save the requested URL (request.original_url) as
session [: forwarding_url] in 1. ʻIf request.get?` limits the request type to GET actions only.
3 is the process to return to the temporarily saved URL or to return to the URL specified as the default. Even if the URL does not exist
||After that, the URL set in default can be entered.
Also, if you keep the session information, it will be read and strange at the next login, so the URL temporarily saved with
session.delete (: forwarding_url) on the second line in the method Delete.
store_location to temporarily store the URL you are trying to access.
Here, I will write it together with the description to check if the logged-in user is below private of ʻusers_controller.rb`.
class UsersController < ApplicationController before_action :user_login_required ・ ・ ・ private def user_login_required unless logged_in? #When not logged in store_location #Temporarily save the URL here! flash[:danger] = "Please login" #Show flash message redirect_to login_url #Forced to send to login page end end
redirect_back_or (default) to specify the transition destination after login. It is OK if you write the following in the place where the login process is performed.
def create user = User.find_by(email: params[:session][:email].downcase) if user && user.authenticate(params[:session][:password]) log_in user params[:session][:remember_me] == '1' ? remember(user) : forget(user) flash[:success] = "You are now logged" #Specify the redirect destination below. default uses user here, but user_Can be written like url redirect_back_or user else flash.now[:danger] = 'I failed to login' render 'new' end end
This completes the implementation! If you dare to log in after deporting from an existing URL, you will be taken to that URL. Thank you for your support.
As mentioned above, I tried to reorganize each role in my own way so that it is easy to understand at a glance. I hope you find it helpful.
I referred to the following for implementation. Thank you very much.