简体   繁体   English

覆盖设计控制器

[英]Overriding Devise Controller

Experimenting with Devise 3.0 for Rails 4 and thinking about integrating into an existing app to replace my own Authentication system. 尝试使用Devise 3.0 for Rails 4并考虑集成到现有应用程序中以替换我自己的身份验证系统。

My own users_controller communicated with an API (Stripe) during registration and I'm not sure how I would include this functionality if I were to use Devise? 我自己的users_controller在注册期间与API(Stripe)进行了通信,如果我使用Devise,我不确定如何包含此功能?

Am I suppose to override/extend the Devise Controller in some way? 我想以某种方式覆盖/扩展Devise控制器吗? Any help would be much appreciated. 任何帮助将非常感激。

You can define the actions in the your controller and call super inside it, which will include the functionality of the corresponding devise action. 您可以在控制器中定义操作并在其中调用super ,其中包括相应设计操作的功能。 And you can also add your own functionality into it. 您还可以在其中添加自己的功能。

Eg: Consider the Registrations controller ( Registrations Controller ) 例如:考虑注册控制器( 注册控制器

Here, you can use the devise's create action code of Registration Controller in you own create action of Registration Controller and add your functionality as commented in the code. 在这里,您可以在自己的注册控制器创建操作中使用设计注册控制器的创建操作代码,并在代码中添加您的功能。

class RegistrationsController < Devise::RegistrationsController
  .
  .
  .

  def create
    build_resource(sign_up_params)

    if resource.save
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_navigational_format?
        sign_up(resource_name, resource)
        # Here the user successfully signs up, so you can use your stripe API calls here.
        respond_with resource, :location => after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
        expire_session_data_after_sign_in!
        respond_with resource, :location => after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      respond_with resource
    end

  end

end 

For future googlers: it is possible to call super in an action of inherited controller with block and do whatever you want, without overwriting Devise code: 对于未来的googlers:可以在一个继承控制器的操作中使用块调用super并执行任何你想要的操作,而不会覆盖Devise代码:

class Users::RegistrationsController < Devise::RegistrationsController
  def create
    super do |user|
      NotificationMailer.user_created(user).deliver
    end
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM