ruby rails - redirect to the 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] =
   redirect_to myapp_url, :notice => "Logged in!"
else = "Invalid email or password"
    render "new"


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.