简体   繁体   中英

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.

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.

Would would be the Rails way to do this? Thanks!

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

(Rails 5 Update) You can use redirect_back to return the user to the page they just came from.

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

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