6

Rails 2.3.11

If a user tries to go to /photos when they aren't logged in, they are directed to [site]/admin/login?route=[site]/photos. After they log in, I would like them to be sent to whatever was defined in "route" instead of the default home page.

In /app/controllers/admin_controller.rb:

def login
    if session[:user_id] #already logged in
      redirect_to ''
    @destination = request.url
    end
    if request.post?
      if [authentication code]
        if user.activated? #check to see whether the user has activated their account
          session[:user_id] = user.id
          if params[:route] # ********
            redirect_to "#{params[:route]}"
          else
            redirect_to :controller => 'home'
          end
        else
          flash.now[:notice] = "Your account hasn't been activated yet.  Check your emails!"
        end
      else
        flash.now[:notice] = "Invalid email/password combination"
      end
    end
  end

The "*"ed line is the one that isn't working correctly. When I check to see the parameters, :route isn't among them, so the argument isn't being passed in with the login post. Can anyone explain to me why it isn't and how I could fix it?

Thank you!

1 Answer 1

3

You could do something like:

session[:return_to] ||= request.referer
3
  • 1
    Have a look at stackoverflow.com/questions/2139996/…
    – Swift
    Jul 22, 2011 at 20:57
  • This looks like it should do the trick, but I'm still pretty new at Rails, so could you kindly elaborate a little on where I should put that? Would it go in my application controller (where it redirects visitors who aren't logged in to the log-in page) or somewhere in the method posted above? Thanks!
    – Benjin
    Jul 22, 2011 at 21:09
  • 1
    Thank you; that worked (once I figured it out)! For all others, what I ended up having to do was this: Have a before_filter that directs to an authorization method: def authorize unless logged_in? session[:original_target] = request.request_uri flash[:notice] = "You must be logged in to view that page" redirect_to home_url end end Then, in my login controller, after authenticating the user, check to see whether there's anything stored in session[:original_target] and, if there is, go to that.
    – Benjin
    Jul 24, 2011 at 22:32

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.