簡體   English   中英

登錄重定向到他最近在Rails Devise中的頁面

[英]Sign in redirect to the page where he were lastly in Rails Devise

我想要一個登錄頁面,該頁面將用戶重定向到他登錄之前的最后一個頁面。如何在Rails中做到這一點。 我需要為每個鏈接重寫after_sign_in_path嗎?

謝謝 :)

簡短的回答是,您將需要覆蓋after_sign_in_path 。我發現這樣做的最簡單方法如下:

在應用程序控制器內部,您需要添加兩種方法,

  include SessionsHelper
  def after_sign_in_path_for(resource_or_scope)
    case resource_or_scope
    when :user, User
      store_location = session[:return_to]
      clear_stored_location
      (store_location.nil?) ? requests_path : store_location.to_s
    else
      super
    end
  end

  def check_login
    if !anyone_signed_in?
      deny_access
    end
  end

首先,我們覆蓋after_sign_in_path拯救我們的,我們從Rails的會話進入我們拉動新的存儲位置store_location我們將在我們的定義SessionsHelper 接下來,我們創建一個方法,可以在要使用此方法的任何控制器中將其用作before_filter

接下來,設置sessions_helper.rb

module SessionsHelper

  def deny_access
    store_location
    redirect_to new_user_session_path
  end

  def anyone_signed_in?
    !current_user.nil?
  end

  private

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

    def clear_stored_location
      session[:return_to] = nil
    end

end

在這里,我們只是定義在我們的應用程序控制器內部使用的方法,這些方法都應該很容易解釋。 只需記住要記住其先前路徑的控制器中的before過濾器之前使用before_filter :check_login即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM