[英]Rails 4 - setting belongs_to relationship not working
I have two models, Team
and Plan
. 我有两个模型,
Team
和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. 我正在使用Stripe进行定期计费,并且正在使用
[webhooks][2]
使我的应用程序与Stripe保持同步。 To receive Stripe events I'm using the gem [stripe_event][3]
. 要接收Stripe事件,我正在使用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: 当我收到Stripe事件
customer.subscription.created
,请执行以下操作:
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. 登录后,我确认
team_plan
是正确的计划,并且不是nil。
Any ideas on what I'm doing wrong? 关于我在做什么错的任何想法吗?
Try adding the inverse relationships: 尝试添加逆关系:
#Plan
has_many :teams, inverse_of: :plan
#Team
belongs_to :plan, inverse_of: teams
The inverse relationships help ensure that save
works when you save subobjects. 逆关系有助于确保
save
作品时,你救子对象。
Try looking at the id of each item before and after save: 尝试查看保存之前和之后的每个项目的ID:
p "team_plan.id:#{team_plan.id}, team.plan.id: #{team.plan.id}"
team.plan = team_plan
p "team_plan.id:#{team_plan.id}, team.plan.id:#{team.plan.id}"
team.save!
p "team_plan.id:#{team_plan.id}, team.plan.id:#{team.plan.id}"
If you're comfortable with Rails logger, or pry
, or a debugger, use those instead of print statements. 如果您对Rails记录器,
pry
或调试器感到满意,请使用它们代替print语句。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.