Ruby/Rails:抑制超类函数 - Stripe 和 Devise 的集成

Ruby/Rails: suppress superclass functions - integration of Stripe and Devise

我的 RegistrationsController 中有一个创建方法,它继承自 Devise::Registrations 控制器。它应该调用 Stripe,如果客户创建成功,它会保存用户并发送一封确认电子邮件,由 Devise 中的“#create”处理。如果对 Stripe 的调用失败,它应该设置一个 flash 并且不保存用户或发送电子邮件,即抑制 Devise 'create' 方法。如果对 Stripe 的调用成功,该方法工作正常,但如果不成功,用户仍然被保存,确认电子邮件仍然被发送。

class RegistrationsController < Devise::RegistrationsController

  def create
    super 
    @user = resource
    result = UserSignup.new(@user).sign_up(params[:stripeToken], params[:plan])

    if result.successful?
      return
    else
      flash[:error] = result.error_message
      # TODO: OVERIDE SUPER METHOD SO THE CONFIRM EMAIL IS 
      # NOT SENT AND USER IS NOT SAVED / EXIT THE METHOD
    end
  end

我试过 skip_confirmation!,这只是绕过了确认的需要。 resource.skip_confirmation_notification!也不起作用。我也试过重新定义 resource.send_confirmation_instructions;零;结尾;我的想法是在 else 块中完全退出 create 方法。如何退出 create 方法或在 else 块中抑制 'super',或者另一种方法会更好吗?谢谢

通过在覆盖顶部调用 super,整个注册过程将开始,注册您的用户,然后才执行您的代码。

您需要覆盖 Devise's registrations_controller.rb create action 代码,方法是复制并粘贴整个代码并插入您的调用,如下所示:

class RegistrationsController < Devise::RegistrationsController

  # POST /resource
  def create
    build_resource(sign_up_params)

    # Here you call Stripe
    result = UserSignup.new(@user).sign_up(params[:stripeToken], params[:plan]) 
    if result.successful?
      resource.save
    else
      flash[:error] = result.error_message
    end

    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_flashing_format?
        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}" if is_flashing_format?
        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

请注意 resource.save 仅在 result.successful? 时调用。