问题
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
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
thx
回答1:
Yes, your subscription object won't have an user_id because the user is not persisted yet. There is no id available.
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)
回答2:
I believe that if you want this kind of awareness out of your relations you'll need to add inverse_of
options to them:
User
has_many :subscriptions, inverse_of: :user
Subscription
belongs_to :user, inverse_of: :subscriptions
For more on the inverse_of
option, search this page for the term inverse_of
until you get down to the has_many
code: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods
Does that help?
来源:https://stackoverflow.com/questions/18564224/how-to-use-rails-build-to-create-a-user-with-a-stripe-subscription