如何使用 Rails .build 创建具有条带订阅的用户 [英] How to use Rails .build to create a user with a stripe subscription

查看:32
本文介绍了如何使用 Rails .build 创建具有条带订阅的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Rails + Devise 和 Stripe 进行计费.我正在努力创建一个控制器方法,该方法同时创建一个具有订阅的用户,但遇到了错误.我的控制器方法:

I'm using Rails + Devise along with Stripe for billing. I'm working to create a controller method that creates a user with a subscription at the same time but am running into errors. My controller method:

def signup_w_cc
    @user = User.new(:email => params[:user][:email]
    @user.subscriptions.build(:stripe_card_token => params[:stripe_card_token],
                                              :plan_id => 1,
                                              :quantity => 1)
    @user.save
end

这是失败的,当我执行@user.save 时,订阅模型没有获得所需的 user_id 字段.我是否错误地使用了构建?这个想法不是先创建用户,然后再创建订阅,因为它们都需要同时提交或回滚.

This is failing, when I do @user.save, the subscription model is not getting the required user_id field. Am I using build incorrectly? The idea is not to create the user and then the subscription as they both need to commit or rollback at the same time.

user.rb

  has_many :subscriptions

subscription.rb

belongs_to :user

谢谢

推荐答案

是的,您的订阅对象将没有 user_id,因为用户尚未持久化.没有可用的 ID.

Yes, your subscription object won't have an user_id because the user is not persisted yet. There is no id available.

要修复,首先尝试更改保存用户的顺序.然后 @user.subscription 将附加一个 user_id.

To fix, try to change the order to save user at first. Then @user.subscription will have an user_id attached.

@user = User.new(:email => params[:user][:email]
@user.save # Save and get id at first.
@user.subscriptions.build(:stripe_card_token => params[:stripe_card_token],
                                          :plan_id => 1,
                                          :quantity => 1)

这篇关于如何使用 Rails .build 创建具有条带订阅的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆