Rails重定向到登录前想要查看的页面用户

我正在尝试将用户重定向回他们在登录之前尝试访问的页面(该页面仅供用户查看)。

我将从一个针对我的旅行新动作的前filter开始:

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

 def authenticate deny_access unless signed_in? end def deny_access store_location redirect_to login_path, :notice => "Please log in to access this page." end def store_location session[:return_to] = request.fullpath end 

这是我的sessions_controller.rb中的new和create操作

 def new @title = "Log in" end def create user = User.authenticate(params[:session][:email].downcase, params[:session][:password]) if user.nil? flash.now[:error] = "Invalid email/password combination." @title = "Log in" render 'new' else sign_in user redirect_back_or(root_path) end end def redirect_back_or(default) redirect_to(session[:return_to] || default) clear_return_to end 

谢谢!

编辑:删除了MaddHacker的代码版本,因为这不是我想要的。

我通常使用before_filter之类的

 def login_required session[:return_to] = request.fullpath redirect_to(login_page_url) end 

然后当我的登录完成时,我会在会话中查找return_to:

 def login # user validation of login here url = session[:return_to] || root_path session[:return_to] = nil url = root_path if url.eql?('/logout') logger.debug "URL to redirect to: #{url}" redirect_to(url) end 

好吧,首先,您需要在从未授权页面重定向到登录页面之前调用store_return_to方法。 然后我认为您需要将方法描述更改为def redirect_back_or_default(default = root_path)以便参数变为可选。

顺便说一句,我不能理解为什么你需要将参数传递给该方法,如果它只是一个默认值,你可以在方法本身硬编码。