Return user to previous page after login (Rails)

后端 未结 2 1285
花落未央
花落未央 2020-12-28 20:34

On a rails 2.3.8 site I have login links on each page (that takes a user to a separate signin page). After a successful login the user is currently redirected to root. Inste

相关标签:
2条回答
  • 2020-12-28 20:43

    Instead of trying to redirect to the referrer, I would set the session[:return_to]

    You'll need a before filter that runs before your authentication on all your actions:

    def store_return_to
      session[:return_to] = request.url
    end
    

    Then change your redirect to just be

    redirect_back_or_default()
    
    0 讨论(0)
  • 2020-12-28 20:49

    Before all you must store your url by cookies:

    cookies[:return_to_url] = request.url
    

    And then after success logging:

    redirect_to cookies[:return_to_url] || root_path
    cookies[:return_to_url] = nil
    
    # or even better code in one line:
    redirect_to cookies[:return_to_url].delete || root_path
    

    https://api.rubyonrails.org/classes/ActionDispatch/Cookies.html

    0 讨论(0)
提交回复
热议问题