Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Devise redirect to a stored location after sign in or sign up?

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.

like image 746
John Avatar asked Mar 10 '11 03:03

John


2 Answers

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.

like image 197
John Avatar answered Sep 19 '22 22:09

John


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.

like image 24
asok Avatar answered Sep 21 '22 22:09

asok