How do I make Devise redirect to a stored location

2019-02-10 13:04发布

问题:

I'm using Devise in a Rails application I'm writing, and I want to let users go back to where they were after signing in or signing up.

For example, if I have a "comments" Controller that is protected by:

before_filter :authenticate_user!

Then I want users who click a "Comment Now!" button (and are therefore redirected to the new action in CommentsController) to log in and then have Devise redirect them to the new action (or wherever they were) in CommentsController, not to the generic root of the application, or to a generic after_sign_in_path.

Looking through the RDOC for Devise, I found this method that makes it look as if Devise has at least the capability to do something like this on its own, but I can't figure out a way.

回答1:

OK, so I've done some more experimentation, and working with Kormie's info, I've got a working solution.

From what I can determine, before_filter authenticate_user! does not save the route for returning the user. What I did was this:

First, I added an extra before_filter at the top of my controller

before_filter :store_location
before_filter :authenticate_user!

Then, I wrote the store_location method at the bottom of the controller

private

  def store_location
    session[:user_return_to] = any_old_route_path
  end

I don't claim this is perfect, but it works for me. (The downside for anyone else wanting to use it, is that it only supports one return path per controller. This is all I need for myself, but it is only a slight improvement over the one return path per app that I was using previously.) I would really appreciate anyone else's insights and suggestions.



回答2:

Devise should do this by itself. The authenticate_user! filter also did not want to work for me when the route to the action was set via PUT method. When I have changed this to GET in routes.rb devise started to work as expected.



回答3:

The simple way to do this:

# Modified from https://github.com/plataformatec/devise/wiki/How-To:-redirect-to-a-specific-page-on-successful-sign-in
class ApplicationController < ActionController::Base
  def after_sign_in_path_for(resource)
    stored_location_for(resource) || your_defaut_path 
  end
end


回答4:

I think by default Devise saves the route but you may be usinging

sign_in @user

this should redirect you

sign_in_and_redirect(@user) #assuming you are sigining in that resource


回答5:

Have you tried after_sign_in_path_for? If you define that method in your ApplicationController it should override the default implementation on a per controller basis.