0

我正在尝试重定向到单击登录的页面,但是登录后它不会重定向到上一页而是停留在登录页面上(尽管用户已经登录)。这是我的代码:

session_helper.rb

module SessionsHelper

def sign_in(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.encrypt(remember_token))
    self.current_user = user
end


def redirect_back_or(default)
    redirect_to(session[:return_to] || default)
    session.delete(:return_to)
end

def store_location
    session[:return_to] = request.fullpath
end
end

session_controller.rb

class SessionsController < ApplicationController
  include SessionsHelper
  def new
  end
  def create
    user = User.find_by_username(params[:session][:username])
    if user && user.authenticate(params[:session][:password])   
      cookies.permanent[:remember_token] = user.remember_token
      #redirect_to root_url,:notice => "Logged in!"
        redirect_back_or user
    else
      flash[:error] = 'Invalid email/password combination' # Not quite right!
      render 'new'
    end
  end
  def destroy
    cookies.delete(:remember_token)
    #session[:user_id] = nil
    redirect_to root_url, :notice => "Logged out!"
  end
end

我还尝试在 sessions_controller.rb 中编写创建函数

redirect_to request.referer

但它不起作用。

我错过了什么吗?

谢谢你的帮助!

4

2 回答 2

0

The problem happens at store_location.

Though you havn't said in question, I guess you probably put this method in before_filter. So, no matter GET or POST or other request, the request hit this filter at first and store location.

Now, in this case, actually the user has two requests. One is to #new by GET, and the other is to #create by POST. In the later, his last request to #new was recorded as the going back location. So you'll see you always go back to #new :)

The solution is to filter the location to be stored.

def store_location
  disable_pattern = /\A\/user*/
  session[:return_to] = request.fullpath unless request.fullpath ~= disable_pattern
end

This pattern could solve current problem but not exclusive. In practice you may see even JS/JSON requests has been recorded, so you may need to add more restrictions according to the specific case. For example, only apply before_filter on #show or #index, use white list, etc.

于 2013-11-13T14:50:46.760 回答
0

我认为request.referer可能由于方法中的拼写错误而无法正常工作。应该是request.referrer

于 2015-08-21T20:38:34.787 回答