Majoris
Majoris

Reputation: 3189

ruby rails - redirect to original request url

Here is what I have for redirecting to a default url(myapp_url). But I want to change redirect to go the request url was entered by the user after authentication. How do I do that? I tried couple of options from searching here, like :back. But no go.

User enters an url, if not authenticated then gets redirected to the login page, then after login user shall be redirected to the original request url.

def create
   user = User.Authenticate(params[:user_id], params[:password])
 if user
   session[:user_id] = user.id
   redirect_to myapp_url, :notice => "Logged in!"
else
    flash.now.alert = "Invalid email or password"
    render "new"
  end

end

Upvotes: 13

Views: 13884

Answers (2)

You can read the chapter about "Friendly forwarding" in the "Ruby on Rails Tutorial" by Michael Hartl to see how you can easily implement it.

Basically you have 3 helper methods:

  1. store_location to store the user desired location in the session
  2. redirect_back_or(url) redirect the user to the location stored in the session or, if not set, to the location contained in the url method param
  3. and clear_return_to used "internally" by the redirect_back_or method to clear this piece of information once used

And then you use these methods:

A) when you see a guest user try to access a page that needs authentication use store_location before redirect him to the login page.
B) when a user is logged in, you use redirect_back_or(url) to redirect him to the right location (if present of course)

This is an overview of how this work, you get the idea but I suggest to read that chapter for the implementation (few) details.

Upvotes: 16

mikdiet
mikdiet

Reputation: 10018

You need to save path in session before redirection on authentication, and after successful auth redirect to this path.

Upvotes: 1

Related Questions