You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails调用Stripe API遇ArgumentError:参数数量不匹配问题

问题分析与解决方案

错误根源

你自定义的Stripe模块与官方Stripe gem的顶级模块发生了命名冲突。当你调用Stripe::Customer.create时,Ruby实际定位到的是你自己在stripe_client.rb中定义的Stripe::Customer类,而非官方Stripe库提供的类。而你自定义的这个类的initialize方法不接受参数,但调用过程中传入了参数,因此触发ArgumentError。

解决方案

1. 重命名自定义模块

避免与官方gem模块同名,将你的自定义模块改为独特名称(比如AppStripe),彻底解决冲突:

修改后的customer_api.rb代码:

require 'stripe'
module AppStripe
  class CustomerApi
    def initialize(id)
      @user = User.find(id)
      @company_profile = @user.company_profile
      Stripe.api_key = 'my test key info'
    end

    def create_stripe_customer
      request = Stripe::Customer.create({
        email: 'test@example.com',
        name: 'john doe',
        address: {
          city: 'Brothers',
          country: 'US',
          line1: '27 Any Street',
          postal_code: '90210',
          state: 'CA',
        }
      })

      Rails.logger.info request
    end
  end
end

之后在控制台调用时使用新的模块名:

AppStripe::CustomerApi.new(30).create_stripe_customer

2. 清理冲突类定义

检查stripe_client.rb文件,确认是否存在Stripe::Customer类的自定义实现。如果该文件是用于REST API调用的独立尝试且不再需要,可直接删除;若需保留,同样要将其移至自定义模块下(比如AppStripe::CustomerClient),避免与官方类名冲突。

额外提示

Ruby的模块是全局命名空间,直接使用与第三方gem相同的顶级模块名会导致类/方法覆盖,引发难以排查的错误。后续开发中建议为业务代码使用专属的顶级模块(比如以你的应用名称命名),隔离第三方库的命名空间。

内容的提问来源于stack exchange,提问作者John Gerard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 03:42:40