如何在Devise中自定义控制器以进行注册?

时间:2011-05-01 22:09:51

标签: ruby-on-rails controller devise

当新用户通过Devise注册时,我需要添加一些简单的方法和操作。

我想申请一个发送电子邮件给我的通知方法。

我想使用acts_as_network传递会话值并将新注册表连接到邀请他们的人。

我如何定制,我查看了文档,但我并不完全清楚我需要做什么....谢谢!

1 个答案:

答案 0 :(得分:15)

我正在做的事情是覆盖Devise Registrations控制器。我需要捕获在注册新用户时可能引发的异常,但您可以应用相同的技术来自定义注册逻辑。

应用/控制器/设计/定制/ 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

请注意,我在devise/custom下创建了一个新的app/controllers目录结构,我在其中放置了RegistrationsController的自定义版本。因此,您需要将设计注册视图从app/views/devise/registrations移至app/views/devise/custom/registrations

另请注意,覆盖设备注册控制器允许您自定义一些其他内容,例如在成功注册后重定向用户的位置。这是通过覆盖after_sign_up_path_for和/或after_inactive_sign_up_path_for方法完成的。

<强>的routes.rb

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

post可能会提供您可能感兴趣的其他信息。