1

我正在使用 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.
4

2 回答 2

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将其设置为nil是不够的:

  # application_controller.rb
  def redirect_back_or_default(default)
    redirect_to(session.delete(:return_to) || default)
  end
于 2013-05-19T02:22:20.767 回答
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
于 2013-05-19T03:06:35.233 回答