登录后重定向到以前的URL - Rails

age*_*217 5 authentication ruby-on-rails

对于我正在编写的应用程序,我使用简单的手工身份验证(如Railscast.com上所述).使用Ryan Bates的NiftyGenerators gem中的一些代码,我有一个身份验证模型,它有一些有用的身份验证方法.该模块包含在内application_controller.rb.

我想要使​​用的方法之一是调用redirect_to_target_or_default.我知道这是我需要将用户重定向到他们经过身份验证后所在的页面,但我不知道应该在哪里调用此方法?如果有人能给我一个如何使用这种方法的想法,我将不胜感激.

ControllerAuthenticaion模块代码

module ControllerAuthentication
  # Makes these methods helper methods in the controller that includes this module.
  def self.included(controller)
    controller.send :helper_method,
      :current_admin, :logged_in?,
      :redirect_to_target_or_default
  end 

  def current_admin
    @current_admin ||= Admin.find(session[:admin_id]) if session[:admin_id]
  end

  def logged_in?
    current_admin
  end

  def login_required
    unless logged_in?
      store_target_location
      redirect_to login_url,
        :alert => "You must first log in before accessing this page."
    end
  end 
  def redirect_to_target_or_default(default, *args)
    redirect_to(session[:return_to] || default, *args)
    session[:return_to] = nil
  end 
  def redirect_to_or_default(target, *args)
    redirect_to(target || default, *args)
  end 
  def store_target_location
    session[:return_to] = request.url
  end
end
Run Code Online (Sandbox Code Playgroud)

flo*_*ooo 3

您是否在 Ryan 的宝石中运行了发电机?它应该已经为您生成了一个 SessionController (请参阅链接),其中还包含此方法:

def create
  @session = Session.new(params[:session])
  if @session.save
    flash[:notice] = "Logged in successfully."
    redirect_to_target_or_default(root_url)
  else
    render :action => 'new'
  end
end
Run Code Online (Sandbox Code Playgroud)

我认为您在阅读这段代码时可以了解如何使用它。:)