繁体   English   中英

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

[英]Redirecting to previous URL after login - 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

你在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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM