devise (3.5.2)
うわー、これはすべて舞台裏 (Devise::SessionsController#new
アクションの周り) で自動的に行われることに気付きました。追加のコントローラーの変更は必要ありません。
store
明示的に/ get
previousする必要がある場合location
は、以前の回答を参照してください。
現在(2015年秋)、よりセクシーな方法があります:
Devise::Controllers::StoreLocation#store_location_for
:
# Stores the provided location to redirect the user after signing in.
# Useful in combination with the `stored_location_for` helper.
store_location_for :user, dashboard_path
redirect_to user_omniauth_authorize_path :facebook
Devise::Controllers::StoreLocation#stored_location_for
:
# Returns and delete (if it's navigational format) the url stored in the session for
# the given scope. Useful for giving redirect backs after sign up:
redirect_to stored_location_for(:user) || root_path
メソッドは、読み取り後に関連するsession
キーと値の削除を処理します。必要なのは、:resource
キー (:user
上記の例) と保存するパス (上記の例)を提供することだけですdashboard_path
。詳細はソース参照。
実際の答えについては、次のようになります。
class ApplicationController < ActionController::Base
rescue_from CanCan::AccessDenied, with: :access_denied
# ...
private
def access_denied(exception)
store_location_for :user, request.path
redirect_to user_signed_in? ? root_path : new_user_session_path, alert: exception.message
end
def after_sign_in_path_for(resource)
stored_location_for(:user) || root_path
end
end