Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 770
Majoris Avatar asked Apr 07 '12 06:04

Majoris


1 Answers

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.

like image 125
Aldo 'xoen' Giambelluca Avatar answered Nov 01 '22 22:11

Aldo 'xoen' Giambelluca