ruby rails - redirect to original request url

ruby, ruby-on-rails, ruby-on-rails-3

Solution

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:

- `store_location` to store the user desired location in the session

- `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

- 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.

Problem

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 ```

Original source

Related problems