简体   繁体   中英

Redirect to page before login

right now I have a problem with login. I want the user to go the previous page where he/she pressed the login-button. In my code right now I just have redirect_to back which just sends the user back one level but I want it to be two levels. How do I do that?

class SessionsController < ApplicationController
    def new
    end

    def create
        user = User.find_by(email: params[:session][:email].downcase)
        if user && user.authenticate(params[:session][:password])
            sign_in user
            redirect_to back
        else
            flash.now[:error] = 'Invalid email/password combination'
            render 'new'
        end
    end

    def destroy
        sign_out
        redirect_to root_url
    end

end

Thanks!

The simplest solution is to probably follow the outline that the devise gem provides in their how-to. TL;DR - store the path in the session and use that as your redirect after sign in.

one of the solution maybe store the url inside the cookies, and redirect to that url after sign in

cookies[:return_to] = {
  value: request.fullpath, 
  expires: 1.hour.from_now
}

redirect_to sign_in_path

after login, just call

path = cookies[:return_to]
cookies.delete(:return_to)
redirect_to path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM