4

我試圖將用戶重定向到他們在登錄之前嘗試訪問的頁面(該頁面只對用戶可見)。Rails重定向到頁面用戶想要在登錄之前查看

我會與前過濾器,針對我的旅行新的行動開始:

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創建操作

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的我的代碼版本,因爲這不是我想要的。

+0

解決的問題。在我重定向到登錄頁面之前,我只需在控制器中添加'store_location'。 – Huy

回答

3

我通常使用像

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

然後當我登錄完成了的before_filter,我認準的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 
+0

我試過使用你的代碼;但是,我仍然被重定向回root_path,因此看起來像我的會話[:return_to]沒有存儲完整路徑。我已將我的代碼版本添加到我的帖子中。 – Huy

+0

此外,這種方式只在我登錄後存儲會話。 – Huy

+0

嘗試添加logger.debug語句以查看您要去哪裏(我還建議檢查註銷url,因爲點擊註銷時遇到了一些問題,然後嘗試再次登錄)。就像一個筆記一樣,我建議你只在會話中存儲用戶的電子郵件地址(安全事物),只需鍵入登錄即可。 – MaddHacker

0

那麼,首先你需要在從未經授權的頁面重定向到登錄頁面之前調用store_return_to方法。那麼我認爲你需要將方法描述改爲def redirect_back_or_default(default = root_path)之類的東西,所以參數變成可選的。

順便說一句,我不能真正理解爲什麼你需要傳遞一個參數到該方法,如果它只是一個默認值,那麼你可以在方法本身進行硬編碼。

+0

我在重定向到登錄頁面之前嘗試調用store_return_to方法,但仍然被重定向到默認路徑。代碼添加到原始文章。 – Huy

相關問題