2

我已经尝试了几个小时来解决这个问题。我可以在我的付款模型 payment.rb 中使用此代码成功付款:

def save_with_payment
if valid?
  customer = Stripe::Customer.create(description: email, card: stripe_card_token)
  self.stripe_customer_token = customer.id
  save!

  Stripe::Charge.create(
      :amount => (total * 100).to_i, # in cents
      :currency => "usd",
      :customer => customer.id
  )
end
rescue Stripe::InvalidRequestError => e
logger.error "Stripe error while creating customer: #{e.message}"
errors.add :base, "There was a problem with your credit card."
false
end

我想在我的用户模型中将 Stripe 的 customer.id 保存到我的用户表属性 customer_id 但上面的代码在我的付款模型中,我该怎么做?

Stripe 的帮助部分说,通过执行以下操作很容易:

save_stripe_customer_id(user, customer.id)

然后稍后:

customer_id = get_stripe_customer_id(user)

Stripe::Charge.create(
:amount => 1500, # $15.00 this time
:currency => "usd",
:customer => customer_id
)

我在 save_stripe_customer_id 中输入了什么代码?我把那个代码放在哪里?上面为我工作的生成 Stripe 的 customer.id 的方法在 Payment 模型中,但我想将其保存为我的 User 模型中的一个属性,这样我就可以稍后向用户收费,而不必重新输入他们的信用卡。如何将 Payment 模型中生成的内容保存到我的 users 表中?

编辑:

付款.rb

belongs_to :user

用户.rb

has_many :payments

我想作为 customer_id 添加到我的用户表中的属性已经在我的支付表中作为 stripe_customer_token,我只是不知道如何在其中使用它或如何将其转移到我的用户表中。

更多的:

付款控制器.rb:

def create
if current_user
  @payment = current_user.payments.new(params[:payment])
else
  @payment = Payment.new(params[:payment])
end
respond_to do |format|
  if @payment.save_with_payment
    format.html { redirect_to @payment, notice: 'Payment was successfully created.' }
    format.json { render json: @payment, status: :created, location: @payment }
  else
    format.html { render action: "new" }
    format.json { render json: @payment.errors, status: :unprocessable_entity }
  end
end
  end

可能的原因

self.user.update_attribute(customer_id, customer.id)

是否因为涉及用户而为 customer_id 抛出一个未定义的方法与 Devise 有某种关联?我的路线文件中是否需要更改某些内容?

路线.rb

devise_for :users, :path => 'accounts' do
get 'users', :to => 'store#index', :as => :user_root
end

resources :users

resources :payments

match ':controller(/:action(/:id))(.:format)'
4

1 回答 1

2

试试这个

def save_with_payment
if valid?
  customer = Stripe::Customer.create(description: email, card: stripe_card_token)
  self.stripe_customer_token = customer.id
  self.user.update_attribute(:customer_id, customer.id) #this will update your user
  save!

  Stripe::Charge.create(
      :amount => (total * 100).to_i, # in cents
      :currency => "usd",
      :customer => customer.id
  )
end
rescue Stripe::InvalidRequestError => e
logger.error "Stripe error while creating customer: #{e.message}"
errors.add :base, "There was a problem with your credit card."
false
end
于 2012-12-24T20:26:20.797 回答