[英]How to return to previous page after Devise sign in
通過Devise成功登錄后,如何將用戶重定向回他們所在的頁面?
我已經閱讀和搜索了很多,我知道我需要定義after_sign_in_path_for
。 我已經完成了這個並且它正常工作,我遇到的問題是理解上一頁的存儲方式,以及如何正確調用它。
我在會話控制器中有這個:
def after_sign_in_path_for(resource)
return request.env['omniauth.origin'] || session[:user_return_to] || root_path
end
我也試過了
...
return request.env['omniauth.origin'] || stored_location_for(resource) || root_path
...
我不認為我理解如何存儲位置,因為如果用戶單擊登錄,則會將用戶重定向回根路徑。
登錄可以通過兩種方式啟動。 (a)用戶嘗試訪問受限視圖(即before_filter :authenticate_user!...
,在這種情況下,它們被重定向並提示登錄。或者(b)用戶單擊每個頁面上可用的登錄鏈接如果用戶未登錄
(a)似乎有效。 (b)不是。 我想我需要在用戶點擊登錄鏈接時將當前位置存儲到會話。
我該怎么做呢? 或者,哪里有一個很好的信息來源,可以幫助我理解這一點。
謝謝!
你可以使用request.referrer
獲取前一個url,如下所述: 如何在Ruby On Rails中重定向到上一頁?
采用
redirect_to request.referrer
抬頭:代碼應該放在application_controller.rb中,而不是會話控制器。
它的工作原理是較新版本的Devise自動存儲用戶試圖訪問的初始頁面(在重定向到登錄之前)。
可以使用設計幫助器訪問: stored_location_for(resource)
您添加到應用程序控制器的內容是這樣的:
def after_sign_in_path_for(resource)
stored_location_for(resource) || users_dashboard_path
# replace users_dashboard_path by whichever route you want to redirect to after login - default is root_path
end
成功登錄后,Devise將自動從應用程序控制器運行您的方法,而不是自己的方法(覆蓋它)。
對於更復雜的示例,這是來自Devise團隊的示例:
def after_sign_in_path_for(resource)
stored_location_for(resource) ||
if resource.is_a?(User) && resource.can_publish?
publisher_url
else
super
end
end
我希望這個答案可以幫助任何人搜索如何使用更新版本的設備進行此操作。
這是另一種方法。 我只在某些鏈接上啟用此“返回”功能(通過continue
URL參數)。 在下面的例子中,我在檢查params[:continue]
之前將其分配給after_action
中的session[:continue]
- 盡管如果你有授權,這可能是不必要的 。 最后,在after_sign_in_path_for
方法覆蓋中我刪除 session[:continue]
同時使用它(因為之后不需要) - 刪除鍵/值對如果鍵匹配則返回值,否則返回nil
,在這種情況下語句回到root_path
。
應用程序/視圖/雜志/ show.html.erb
<%= link_to 'sign in', new_user_session_path(continue: journal_url(@journal)) %> or
<%= link_to 'sign up', new_user_registration_path(continue: journal_url(@journal)) %>
應用程序/控制器/ application_controller.rb
after_action :store_location
def store_location
if params[:continue] =~ /\/(journal\/[0-9]+|foo|bar)\z/ # safelist
session[:continue] = params[:continue]
end
end
def after_sign_in_path_for(resource)
session.delete(:continue) || root_path
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.