【问题标题】:Ruby/Rails: suppress superclass functions - integration of Stripe and DeviseRuby/Rails:抑制超类函数 - Stripe 和 Devise 的集成
【发布时间】:2015-04-07 23:00:24
【问题描述】:

我的 RegistrationsController 中有一个 create 方法,它继承自 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 方法。如何退出创建方法或在 else 块中抑制“超级”,或者另一种方法会更好?谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby devise stripe-payments


    【解决方案1】:

    通过在覆盖顶部调用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? 时被调用。

    【讨论】:

    • 这行得通,谢谢。我必须在控制器的私有方法中定义“设置最小密码长度”,我从 DeviseController 得到它。我还将下一行 'respond_with resource' 更改为 ,redirect_to new_user_registration_path(plan: params[:plan])' 以便注册失败或信用卡交易将用户引导到相同的注册页面。
    • 很高兴知道!如果您认为它对其他人有帮助,您可以编辑我的答案。
    猜你喜欢
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2012-01-16
    • 2016-02-17
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多