2016-04-21 143 views
3

我想在登录后将用户重定向到同一页面。这种情况是,如果用户未登录,用户将被重定向到登录页面。在登录页面上,当他点击其中一个可用用户选项时,我想存储user_id,然后将其重定向到相同的用户选项他来自哪个页面。 对于这一点,我用下面的代码:登录后将用户重定向到同一页面(Rails)

在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 

在SigninController:

class SigninController < ApplicationController 
def index 
session[:user] = params[:user_id] 
redirect_to session[:referer] 
end 
end 

在登入/索引页:

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 %>

我得到的错误:

user_id没有被保存,而重定向时,我得到一个错误,说session [:referer]是nil。

请解释一下我做错了

+0

当你这样做:'如果request.format.html? ''在'''''''''''''''''''''''''''那就是为什么'会议[:referer]'是零。 – 7urkm3n

+0

你在哪里保存'referrer'到会话? –

+0

在会话[:referer]中。如果用户未登录,它将被保存。请查看application_helper.rb @Hieu Pham –

回答

2

要调用它异步if request.format.html?然后要求的格式是html?returns false。由于它returns false您无法存储此会话session[:referer] = request.url

另外Rails也有redirect_to :back选项。试试这个下面首先,让我知道...

助手:

module ApplicationHelper 
    def check_signed_in 
    if session[:user] 
     session[:referer] = request.url 
    end 
    end 
end 

控制器:

class SigninController < ApplicationController 
    include ApplicationHelper 

    def index 
    check_signed_in 
    session[:user] = params[:user_id] 
    redirect_to session[:referer] 
    end 
end 
+0

谢谢。试过但没有工作。发生了什么:当我尝试访问索引页时,它正在带我登录页面(因为我没有登录)。在登录页面中,它正在调用上一页。这是一个递归行为,最后它崩溃了。我永远无法看到登录页面选择一个选项。你能推荐一些其他的方式吗?谢谢! –

+0

@MouryaKoluguri我只是dnt知道你如何实现它。但看看这本书,他在转发url - >'https:// www.railstutorial.org/book/updating_and_deleting_users'时有一个很好的例子,就像'session [:forwarding_url]'一样搜索它。 – 7urkm3n

相关问题