I have two models, Team
and Plan
. Team has a one to many relationship with plans, where plans can have many teams and each team have one plan. It looks like this:
#Plan
has_many :teams
#Team
belongs_to :plan
I'm using Stripe for recurring billing, and I'm using [webhooks][2]
to keep my app synced with Stripe. To receive Stripe events I'm using the gem [stripe_event][3]
. When subscriptions are created I want to set the plan to the newly created subscription plan. When I get the Stripe event customer.subscription.created
I do the following:
events.subscribe 'customer.subscription.created' do |event|
team = Team.find_by_stripe_customer_id(event.data.object.customer)
create_subscription_for_team(team, event.data.object)
# In this methods I want to set my plan
set_team_plan(team, event.data.object.plan)
end
def set_team_plan(team, plan)
team_plan = Plan.find_by_stripe_id(plan.id)
team.update_attribute(plan_id: team_plan.id)
end
I don't get any errors what I can see, but the plan don't seem to get updated. I have also tried:
team.plan = team_plan
team.save!
But this gives me the same result. When I have logged I have confirmed that team_plan
is the correct plan, and is not nil.
Any ideas on what I'm doing wrong?
Try adding the inverse relationships:
The inverse relationships help ensure that
save
works when you save subobjects.Try looking at the id of each item before and after save:
If you're comfortable with Rails logger, or
pry
, or a debugger, use those instead of print statements. :)