I want to redirect the user to the same page after login. The scenario is that the user will be redirected to a signin page if he is not logged in. On the signin page, when he clicks on one of the available user options, I want to store the user_id and then redirect him back to the same page where he came from. For this, I'm using the following code:
In application_helper.rb:
module ApplicationHelper
def check_signed_in
if session[:user] == nil
if request.format.html?
session[:referer] = request.url
redirect_to signin_index_path
else
@error = 'Please Signin!'
@forward_page = '/signin'
render 'signin/show_signin.js'
end
end
end
end
In SigninController:
class SigninController < ApplicationController
def index
session[:user] = params[:user_id]
redirect_to session[:referer]
end
end
In signin/index page:
We simulate a signin here. Click on an user and you will logged in as the selected user and you will be redirected the previous page.
<%= link_to 'Sam', controller:"signin", action: "index" , user_id: 284542812, remote: true %> <%= link_to 'Marge', controller:"signin", action: "index" , user_id: 604700687, remote: true %>
Error that I'm getting:
the user_id is not being saved and while redirecting I get an error saying that session[:referer] is nil.
Please explain what am I doing wrong
You are calling it async if request.format.html?
then asking a format is html?
it returns false
. Since it returns false
you are not able to store this session session[:referer] = request.url
.
Also Rails has redirect_to :back
option too. Try this below first, and let me know...
Helper:
module ApplicationHelper
def check_signed_in
if session[:user]
session[:referer] = request.url
end
end
end
Controller:
class SigninController < ApplicationController
include ApplicationHelper
def index
check_signed_in
session[:user] = params[:user_id]
redirect_to session[:referer]
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.