条带未定义的方法customer_id

时间:2018-09-18 06:40:37

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

因此,我目前具有此预订功能,正在尝试使用 Stripe

添加付款系统

但是,当我尝试提交信用卡详细信息表格时,出现此错误:

NoMethodError (undefined method `customer_id' for #<User:0x552abc0>):

app/services/credit_card_service.rb:8:in `create_credit_card'
app/controllers/charges_controller.rb:9:in `create' 

当我查看上面的错误中指定的文件中的代码时,这是存在的:

#app/controllers/charges_controller.rb


class ChargesController < ApplicationController

  before_action :authenticate_user!
  before_action :find_product

  def create
    stripe_card_id =
      if params[:credit_card].present?
        CreditCardService.new(current_user.id, card_params).create_credit_card
      else
        charge_params[:card_id]
      end

    Stripe::Charge.create(
      customer: current_user.customer_id,
      source:   stripe_card_id,
      amount:   @booking.price_in_cents,
      currency: 'usd'
    )

    if params[:credit_card].present? && stripe_card_id
      current_user.credit_cards.create_with(card_params).find_or_create_by(stripe_id: stripe_card_id)
    end
  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to @booking
  end

  private

  def card_params
    params.require(:credit_card).permit(:number, :month, :year, :cvc)
  end

  def charge_params
    params.require(:charge).permit(:card_id)
  end

  def find_product
    @booking = Booking.find(params[:booking_id])
  rescue ActiveRecord::RecordNotFound => e
    flash[:error] = 'Booking not found!'
    redirect_to root_path
  end
end

class CreditCardService
  def initialize(user_id, card)
    @user = User.find(user_id)
    @card = card
  end

  def create_credit_card
    customer = Stripe::Customer.retrieve(@user.customer_id)
    customer.sources.create(source: generate_token).id
  end

  def generate_token
    Stripe::Token.create(
      card: {
        number: @card[:number],
        exp_month: @card[:month],
        exp_year: @card[:year],
        cvc: @card[:cvc]
      }
    ).id
  end
end

对于解决此问题的任何帮助或提示,将不胜感激。

我已使用devise进行用户登录/注册

2 个答案:

答案 0 :(得分:0)

Afaik,

您需要在Stripe本身中创建客户

例如:

-D_GLIBCXX_USE_CXX11_ABI=0

然后使用

将响应存储在新的迁移列中

response = Stripe::Customer.create({ email: 'email@example.com' })

答案 1 :(得分:0)

如果我没看错的话,看来您的User模型上没有customer_id属性。您需要定义它并存储Stripe客户ID(如上面Nithin所述)。