[英]Redirecting the user to the same page after login (Rails)
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.
如果用户未登录,则会将用户重定向到登录页面。在登录页面上,当他点击其中一个可用的用户选项时,我想存储user_id,然后将其重定向到同一页面他来自哪个页面。 For this, I'm using the following code:
为此,我使用以下代码:
In application_helper.rb: 在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: 在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. user_id没有被保存,重定向时我得到一个错误,说会话[:referer]是零。
Please explain what am I doing wrong 请解释我做错了什么
You are calling it async if request.format.html?
if request.format.html?
您将其称为异步if request.format.html?
then asking a format is html?
然后问一个格式是
html?
it returns false
. 它
returns false
。 Since it returns false
you are not able to store this session session[:referer] = request.url
. 由于它
returns false
,因此无法存储此会话session[:referer] = request.url
。
Also Rails has redirect_to :back
option too. Rails也有
redirect_to :back
选项。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.