简体   繁体   English

成功(或以其他方式)登录Rails后进行重定向

[英]Redirecting after a successful (or otherwise) login in Rails

I'm relatively new to Rails, so I've been following Railscasts to get up to speed, and have successfully created a Login function. 我是Rails的新手,所以我一直关注Railscasts以获得最新信息,并成功创建了Login函数。 The code is as follows: 代码如下:

def create

    user = User.find_by_email(params[:email])
      if user && user.authenticate(params[:password])
        if params[:remember_me]
          cookies.permanent[:auth_token] = user.auth_token
        else
          cookies[:auth_token] = user.auth_token
        end
        redirect_to root_url, :notice => "Logged in!"

      else
        flash.now.alert = "Invalid email or password"
        render "new"
      end

  end

However, as the code shows, the user is always redirected to the home page, as indicated by root_url . 但是,如代码所示,始终将用户重定向到主页,如root_url

What I'd like to achieve is something along the following lines: 我想要实现的目标大致如下:

  1. The user is on the "About", "Contact" or whatever page 用户位于“关于”,“联系”或任何页面上
  2. The user clicks the "Login" link and is taken to the login form page 用户单击“登录”链接,然后转到登录表单页面
  3. After successfully (or unsuccessfully) logging in, the user is returned to the "About", "Contact" page or whatever. 成功(或失败)登录后,用户将返回到“关于”,“联系”页面或其他内容。

However, I cannot seem to work out what I should replace root_url with. 但是,我似乎root_url应该用root_url替换的root_url I tried request.referer , but this obviously took me back to the login form (or, rather, a message stating I was already logged in) rather than the page that the user originally accessed the login form from. 我尝试了request.referer ,但这显然使我回到了登录表单(或者,一条消息,表明我已经登录),而不是用户最初从中访问登录表单的页面。

I suppose I could do some sort of switch/case, where I store the referring page in a string or whatever, and redirect back to that, but this sounds a bit clunky and (as with most things Rails) I'm sure there's an easier way that I'm missing! 我想我可以进行某种切换/转换,将引荐页面存储在字符串中或其他内容中,然后重定向回该页面,但这听起来有些笨拙,而且(与大多数Rails一样),我敢肯定更容易错过的方式!

Thanks! 谢谢!

您可以在会话中存储return_to,您可以 此处参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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