设置登录后如何重定向到不同页面(基于某些参数)?

在我的应用程序中,我有两个不同的登录表单来自两个控制器,它们都将通过Devise :: SessionsController签名,问题是在成功登录(或失败)后我需要重定向到特定于控制器的不同页面。 我怎样才能做到这一点。 我目前在我的Devise :: SessionsController中有这个

class SessionsController  resource_name, :recall => "#{controller_path}#failure") return sign_in_and_redirect(resource_name, resource) end def sign_in_and_redirect(resource_or_scope, resource=nil) scope = Devise::Mapping.find_scope!(resource_or_scope) resource ||= resource_or_scope sign_in(scope, resource) unless warden.user(scope) == resource redirect_to dashboard_path end def failure redirect_to index_path end end 

在应用程序控制器

  before_filter :store_location def store_location unless params[:controller] == "devise/sessions" url = #calculate the url here based on a params[:token] which you passed in session[:user_return_to] = url end end def stored_location_for(resource_or_scope) session[:user_return_to] || super end def after_sign_in_path_for(resource) stored_location_for(resource) || root_path end 

如果有人还在寻找解决方法。 我能够通过以下方式解决这个问题:

首先,创建一个inheritance自Devise::SessionsController的Sessions控制器

 class SessionsController < Devise::SessionsController def new get_pre_login_url(request.referer) super end def create @@referer_url super end private def get_pre_login_url(url) @@referer_url = url end def after_sign_in_path_for(resource) # @@referer_url sign_in_url = url_for(:action => 'new', :controller => 'sessions', :only_path => false, :protocol => 'http') if @@referer_url == sign_in_url super else stored_location_for(resource) || @@referer_url || root_path end end end 

您会注意到我正在设置一个类变量( @@variable_name ),我并不热衷于此,但这是我在尝试各种其他方法解决此问题后4小时提出的。 我也要小心,不要过多地使用Devise的控制器并且使用super并且只包括我关心的动作。

接下来,在路线中,您现在可以将Devise的默认值指向上面的Controller。 对于devise_for ,您不需要完全像下面devise_for ,只是引用controllers: { sessions: "sessions" }的部分controllers: { sessions: "sessions" }

 MyPortfolio::Application.routes.draw do devise_for :users, path_names: { sign_in: "login", sign_out: "logout" }, controllers: { omniauth_callbacks: "omniauth_callbacks", sessions: "sessions" } resources :posts do resources :comments end resources :projects do resources :comments end resources :users root :to => 'home#index' get 'login' => 'devise/sessions#new' get 'about_me' => 'about#index' end 

它可能不是DRYest解决方案,但它是我唯一能够将重定向指向原始页面而不是root或无限循环的解决方案。

您可以通过在控制器中定义after_sign_in_path_for方法来执行此操作,您可以在其中自定义此重定向路径。