How do I customize the controller for registration

2020-02-23 04:16发布

问题:

I need to add some simple methods and actions when a new user registers through Devise.

I want to apply a notify method which will send an email to me.

I want to use acts_as_network to pass a session value and connect the new register to the person who invited them.

How do I customize, I looked at the docs, but I'm not entirely clear what I need to do....thanks!

回答1:

This is what I'm doing to override the Devise Registrations controller. I needed to catch an exception that can potentially be thrown when registering a new User but you can apply the same technique to customize your registration logic.

app/controllers/devise/custom/registrations_controller.rb

class Devise::Custom::RegistrationsController < Devise::RegistrationsController
  def new
    super # no customization, simply call the devise implementation
  end

  def create
    begin
      super # this calls Devise::RegistrationsController#create
    rescue MyApp::Error => e
      e.errors.each { |error| resource.errors.add :base, error }
      clean_up_passwords(resource)
      respond_with_navigational(resource) { render_with_scope :new }
    end
  end

  def update
    super # no customization, simply call the devise implementation 
  end

  protected

  def after_sign_up_path_for(resource)
    new_user_session_path
  end

  def after_inactive_sign_up_path_for(resource)
    new_user_session_path
  end
end

Note that I created a new devise/custom directory structure under app/controllers where I placed my customized version of the RegistrationsController. As a result you'll need to move your devise registrations views from app/views/devise/registrations to app/views/devise/custom/registrations.

Also note that overriding the devise Registrations controller allows you to customize a few other things such as where to redirect a user after a successful registration. This is done by overriding the after_sign_up_path_for and/or after_inactive_sign_up_path_for methods.

routes.rb

  devise_for :users,
             :controllers => { :registrations => "devise/custom/registrations" }

This post may offer additional information you might be interested in.