如果已经 signed_in 用户尝试再次注册,则自定义 Devise 重定向

Customize Devise redirect if already signed_in user tries to sign up again

我觉得这超级简单...

我对默认的 Devise Controllers 做了很少的定制,我的 Registrations#New 中的定制旨在确保某些变量可以在视图中访问。我已经阅读了源代码,但不确定如果访问注册页面的用户已经登录,我是否看到重定向用户的行?

基本上如果用户已经登录,如果 s/he 访问注册页面,我想重定向 him/her 到仪表板页面。目前,重定向将转到根页面。

我该如何更改?

我的代码:

class Users::RegistrationsController < Devise::RegistrationsController
def new
  gon.zipcode_list = zipcode_list
  gon.all_invite_codes = all_invite_codes
  selected_plan_array 
  meal_type_array 

  super
end
end

源代码:

def new
  build_resource({})
  set_minimum_password_length
  yield resource if block_given?
  respond_with self.resource
end

路线:

devise_for :users, controllers: { registrations: "users/registrations", sessions: "users/sessions" }

root "staticpages#home" 
#^ the above is where a user is being redirected if s/he is already signed in and visiting the sign up page

基本上我喜欢下面这样的东西

def after_existing_sign_in_path_for(resource)
  dashboard_path
end

源代码中重定向用户的代码是过滤器:require_no_authentication。如果您覆盖 Devise::SessionsController 以跳过该过滤器,您将能够将您的用户重定向到您选择的路径。

像这样:

class Users::SessionsController < Devise::SessionsController
  # Note that all the other actions are handled by Devise::SessionsController
  # (which is in the gem)
  skip_filter :require_no_authentication, only: :new
  def new
    if user_signed_in?
      redirect_to dashboard_path
      return
    end
    super
  end
end