简体   繁体   English

Rails:登录后如何重定向回原始页面

[英]Rails: How to redirect back to original page after login

I'm working on an app which allows the user to browse the site and log in from any page (login link is in the common header). 我正在开发一个应用程序,允许用户浏览网站并从任何页面登录(登录链接在公共标题中)。 Once a successful login occurs, the user is currently redirected from the login page to root_url. 成功登录后,用户当前会从登录页面重定向到root_url。

It would be more friendly to redirect_to the original page. 重定向到原始页面会更友好。 I attempted to store the named route of the originating page into session, but those appear to be objects, so unable to pass. 我试图将原始页面的命名路径存储到会话中,但这些路径似乎是对象,因此无法通过。 Also, not all routes come with the named helpers. 此外,并非所有路线都附带指定的助手。 On the other hand, when I pass the literal path as a string to the redirect_to, eg 'orders/index', Rails interprets the /action as an id parameter and errors out. 另一方面,当我将文字路径作为字符串传递给redirect_to时,例如'orders / index',Rails将/ action解释为id参数并输出错误。

Would would be the Rails way to do this? 会是Rails这样做的方式吗? Thanks! 谢谢!

您可以使用控制器内的request.referrer获取用户来自的页面的URL。

(Rails 5 Update) You can use redirect_back to return the user to the page they just came from. (Rails 5 Update)您可以使用redirect_back将用户返回到他们刚来的页面。

redirect_back(fallback_location: root_path)

This method requires you set a fallback location because the location is pulled from the browser and it's not always guaranteed to be set. 此方法要求您设置后备位置,因为该位置是从浏览器中提取的,并不总是保证设置。

See the rails guides for more on redirect_back 有关redirect_back更多信息,请参阅rails指南

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

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