无论何处定向到登录页面,都会重定向到上一页

时间:2013-05-19 01:34:40

标签: ruby-on-rails ruby authlogic

我正在使用Rails 3.2和Authlogic。我有以下代码:

class ApplicationController < ActionController::Base
  private

  def store_location
    session[:return_to] = request.url
  end

  def redirect_back_or_default(default)
    redirect_to(session[:return_to] || default)
    session[:return_to] = nil
  end
end

class UserSessionsController < ApplicationController  
  before_filter :require_no_user, :only => [:new, :create]
  before_filter :require_user, :only => :destroy

  def new
    @user_session = UserSession.new
    @header_title = "Login"
  end

  def create
    @user_session = UserSession.new(params[:user_session])
    if @user_session.save
      flash[:success] = "Login successful!"
      redirect_back_or_default root_url
    else
      render 'new'
    end
  end

  def destroy
    current_user_session.destroy
    flash[:success] = "Logout successful!"
    redirect_back_or_default root_url
  end
end

此代码非常通用。当我们使用before_filter

  before_filter :require_user, :only => [:new, :edit, :update, :create]

它将自动store_location并将我们重定向回正确的页面。但是,我该怎么做:

  1. 我在posts/1,但require_user
  2. 点击顶部导航栏上的登录链接。
  3. 显示登录页面。
  4. 登录后,我将重定向回posts/1而不是root_url

2 个答案:

答案 0 :(得分:0)

在会话控制器store_location操作中直接呼叫new

# user_sessions_controller.rb
def new
  store_location if session[:return_to].blank?
  @user_session = UserSession.new
  @header_title = "Login"
end

这将首先检查会话哈希中的现有return_to对。您不希望覆盖它,以防万一,例如,由于密码错误,用户被重定向到new操作。

如果已从store_location调用require_user,也会跳过return_to

成功重定向后,您必须从会话哈希中delete # application_controller.rb def redirect_back_or_default(default) redirect_to(session.delete(:return_to) || default) end 对;将其设置为 nil 是不够的:

{{1}}

答案 1 :(得分:0)

我添加了store_referrer_location以使其正常工作:

# application_controller.rb
class ApplicationController < ActionController::Base
  private

  def store_referrer_location
    session[:return_to] = request.referrer
  end
end

# user_sessions_controller.rb
class UserSessionsController < ApplicationController
  def new
    store_referrer_location if session[:return_to].blank?
    @user_session = UserSession.new
    @header_title = "Login"
  end

  ...

  def destroy
    store_referrer_location if session[:return_to].blank?
    current_user_session.destroy
    flash[:success] = "Logout successful!"
    redirect_back_or_default root_url
  end
end