实施 Stripe Connect 时 nil:NilClass 的未定义方法“update_attributes”

Undefined method `update_attributes' for nil:NilClass When Implementing Stripe Connect

我试图在我的 Rails 6 应用程序中实施 Stripe Connect。 我可以成功地将用户重定向到 Stripe on-boarding。

我正在使用 omniauth-stripe-connect gem

我得到 undefined method update_attributes' 对于 nil:NilClassfor theif @user.update_attributes({` line

我收到的错误是在 User 完成后 Stripe On-boarding 我将它们重定向到我的应用程序。下面是我的 OmniauthCallbacksController:

class PetProviders::OmniauthCallbacksController < Devise::OmniauthCallbacksController

  # You should also create an action method in this controller like this:
  # def twitter
  # end

  def stripe_connect
    auth_data = request.env["omniauth.auth"]
    @user = current_pet_provider
    if @user.update_attributes({
      provider_name: auth_data.provider,
      uid: auth_data.uid,
      access_code: auth_data.credentials.token,
      publishable_key: auth_data.info.stripe_publishable_key,
    })
      sign_in_and_redirect @user, event: :authentication
      flash[:notice] = "Stripe Account Created and Connected" if is_navigational_format?
    else
      session["devise.stripe_connect_data"] = request.env["omniauth.auth"]
      redirect_to root_path
    end
  end

  # More info at:
  # https://github.com/plataformatec/devise#omniauth

  # GET|POST /resource/auth/twitter
  # def passthru
  #   super
  # end

  # GET|POST /users/auth/twitter/callback
  # def failure
  #   super
  # end

  # protected

  # The path used when OmniAuth fails
  # def after_omniauth_failure_path_for(scope)
  #   super(scope)
  # end
end

我怀疑current_pet_provider是空的!

如何在 OmniauthCallbacksController 内获得 current_pet_provider

您似乎需要先从 Omniauth 检索@user 才能使用它? https://github.com/omniauth/omniauth#integrating-omniauth-into-your-application

使用下面的代码片段,我首先使用 email 获取用户,然后插入我想要的新数据。

data = auth_data.info
@user = PetProvider.find_by(email: data["email"])

将所有内容放在一起,我的 stripe_connect 方法现在看起来像这样;

def stripe_connect
    auth_data = request.env["omniauth.auth"]
    data = auth_data.info
    @user = PetProvider.find_by(email: data["email"])
   
    if @user
      @user.provider_name = auth_data.provider
      @user.uid = auth_data.uid
      @user.access_code = auth_data.credentials.token
      @user.publishable_key = auth_data.info.stripe_publishable_key
      @user.save!

      redirect_to root_path
      flash[:notice] = "Stripe Account Created and Connected" if is_navigational_format?
    else
      session["devise.stripe_connect_data"] = request.env["omniauth.auth"]
      flash[:error] = "Unable to Connect To Stripe"
      redirect_to root_path
    end
end