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



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

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

控制器身份验证模块代码

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

你是否在瑞恩的宝石中运行了发电机?它应该为您生成一个会话控制器(参考链接(,其中也包含此方法:

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

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

最新更新