Rails 5 设计:更改不成功的注册重定向路径

Rails 5 Devise: Change Unsuccessful registration redirect path

我正在尝试创建一个简单的网站,其中包含登陆页面和登陆页面本身的用户注册表单。

当注册过程中出现表单错误(例如缺少字段)时,我无法弄清楚如何更改设计注册控制器以重定向回登录页面(根路径“/”)。

现在,如果注册成功,表格可以正常使用。但是,如果注册有错误,它会重定向到 /users/sign_up 视图,其中只包含注册表。如果注册过程中出现错误,我需要它redirect/render登录页面。

我已经生成了一个自定义注册控制器,但是现在它只调用 super。

# POST /resource
def create
  super
end

我也查看了 after_sign_up_path_for,但这不起作用,因为该路径仅在成功注册时调用。

考虑到这种设计模式可能很常见,我怀疑解决方案可能很简单,但我不知道该怎么做。

您可以从 here

复制设备注册控制器

您应该可以添加如下内容:

app/controllers/registrations_controller.rb

   class RegistrationsController < Devise::RegistrationsController
      def new
        super
      end

      def create
        build_resource(sign_up_params)
        if resource.save
          #respond_with resource, location: root_path
          return
        else
          #respond_with resource, location: lending_page_path
          return
        end
        yield resource if block_given?
        if resource.persisted?
          if resource.active_for_authentication?
            set_flash_message! :notice, :signed_up
            sign_up(resource_name, resource)
            respond_with resource, location: after_sign_up_path_for(resource)
           else
            set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
            expire_data_after_sign_in!
            respond_with resource, location: after_inactive_sign_up_path_for(resource)
           end
         else
          clean_up_passwords resource
          set_minimum_password_length
          respond_with resource
         end
      end
  end

然后在你的路线中:

devise_for :users, :controllers => {:registrations => 'registrations'}