在 Rails 可安装引擎中覆盖设计注册控制器

Overriding the devise registrations controller in a Rails mountable engine

我在 Rails 引擎 (my_app/components/base) 中使用设计并覆盖注册控制器,以便在成功注册后将用户转到另一个页面。如果我启动 my_app,这会工作得很好,但是出于某种原因,当从为测试引擎而生成的 spec/dummy 应用程序启动引擎时,devise 不使用我的自定义注册控制器。

使用设计的引擎在main_app/components/base

我的自定义控制器是 main_app/components/base/app/controllers/base/users/registrations_controller.rb

module Base
  class Users::RegistrationsController < Devise::RegistrationsController
    layout 'base/application'

    def after_sign_up_path_for(user)
      fail # note: won't get called
      base.welcome_new_user_path(user)
    end    
  end
end

引擎的路线文件是main_app/components/base/config/routes.rb

Base::Engine.routes.draw do

  devise_for :users, {
    class_name: "Base::User",
    module: :devise,
    controllers: { registrations: 'base/users/registrations' }
  }
  get 'users/welcome_new_user/:id' => "users/welcome#show", as: :welcome_new_user
end

rake routes 表示控制器被识别:

cancel_user_registration GET    /users/cancel(.:format)               base/users/registrations#cancel
       user_registration POST   /users(.:format)                      base/users/registrations#create
   new_user_registration GET    /users/sign_up(.:format)              base/users/registrations#new
  edit_user_registration GET    /users/edit(.:format)                 base/users/registrations#edit
                         PATCH  /users(.:format)                      base/users/registrations#update
                         PUT    /users(.:format)                      base/users/registrations#update
                         DELETE /users(.:format)                      base/users/registrations#destroy
       user_confirmation POST   /users/confirmation(.:format)         devise/confirmations#create
   new_user_confirmation GET    /users/confirmation/new(.:format)     devise/confirmations#new
                         GET    /users/confirmation(.:format)         devise/confirmations#show
        welcome_new_user GET    /users/welcome_new_user/:id(.:format) base/users/welcome#show

但是,自定义注册控制器不会在虚拟应用程序中使用,因此无法通过我的 RSpec 测试。如果我以交互方式使用虚拟应用程序,也会发生同样的情况。

问题已解决。实际上问题不是没有调用自定义注册控制器,而是我覆盖了错误的回调函数。

我的意图是在注册后转到 'thank you for registering' 页面,但由于我的用户模型是可确认的,它已注册,但在用户确认其帐户之前仍然处于非活动状态。所以正确的回调函数是 after_inactive_sign_up_path_for 而不是 after_sign_up_path_for.