Rails:在登录或注册后设计重定向到存储位置? [英] Rails: Devise redirect to a stored location after sign in or sign up?

查看:22
本文介绍了Rails:在登录或注册后设计重定向到存储位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写的 Rails 应用程序中使用 Devise,我想让用户在登录或注册后回到他们原来的位置.

I'm using Devise in a Rails application I'm writing, and I want to let users go back to where they were after signing in or signing up.

例如,如果我有一个受以下保护的评论"控制器:

For example, if I have a "comments" Controller that is protected by:

before_filter :authenticate_user!

然后我希望用户点击立即评论!"按钮(因此被重定向到 CommentsController 中的新操作)以登录,然后让设计将它们重定向到 CommentsController 中的新操作(或它们所在的任何位置),而不是应用程序的通用根,或通用 after_sign_in_path.

Then I want users who click a "Comment Now!" button (and are therefore redirected to the new action in CommentsController) to log in and then have Devise redirect them to the new action (or wherever they were) in CommentsController, not to the generic root of the application, or to a generic after_sign_in_path.

查看设计的 RDOC,我发现 this方法使它看起来好像 Devise 至少有能力自己做这样的事情,但我想不出办法.

Looking through the RDOC for Devise, I found this method that makes it look as if Devise has at least the capability to do something like this on its own, but I can't figure out a way.

推荐答案

好的,所以我做了更多的实验,并且使用 Kormie 的信息,我有了一个可行的解决方案.

OK, so I've done some more experimentation, and working with Kormie's info, I've got a working solution.

据我所知,before_filter authenticate_user!不会保存返回用户的路线.我所做的是这样的:

From what I can determine, before_filter authenticate_user! does not save the route for returning the user. What I did was this:

首先,我在控制器顶部添加了一个额外的before_filter

First, I added an extra before_filter at the top of my controller

before_filter :store_location
before_filter :authenticate_user!

然后,我在控制器底部写了store_location方法

Then, I wrote the store_location method at the bottom of the controller

private

  def store_location
    session[:user_return_to] = any_old_route_path
  end

我不认为这是完美的,但它对我有用.(对于其他想要使用它的人来说,它的缺点是每个控制器只支持一个返回路径.这就是我自己所需要的,但这只是比我之前使用的每个应用程序一个返回路径略有改进.) 我真的很感激其他人的见解和建议.

I don't claim this is perfect, but it works for me. (The downside for anyone else wanting to use it, is that it only supports one return path per controller. This is all I need for myself, but it is only a slight improvement over the one return path per app that I was using previously.) I would really appreciate anyone else's insights and suggestions.

这篇关于Rails:在登录或注册后设计重定向到存储位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆