登录后将用户重定向到同一页面(Rails)

时间:2016-04-21 16:05:07

标签: ruby-on-rails redirect login

我希望在登录后将用户重定向到同一页面。如果用户未登录,则会将用户重定向到登录页面。在登录页面上,当他点击其中一个可用的用户选项时,我想存储user_id,然后将其重定向到同一页面他来自哪个页面。 为此,我使用以下代码:

在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没有被保存,重定向时我得到一个错误,说会话[:referer]是nil。

请解释我做错了什么

1 个答案:

答案 0 :(得分: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