Rails 4 - 设置belongs_to关系不起作用

时间:2014-11-23 21:17:27

标签: ruby-on-rails ruby stripe-payments belongs-to

我有两个模型,TeamPlan。团队与计划有一对多的关系,计划可以有很多团队,每个团队都有一个计划。它看起来像这样:

#Plan
has_many :teams

#Team
belongs_to :plan

我使用Stripe进行定期结算,并且我使用[webhooks][2]让我的应用与Stripe保持同步。要使用gem [stripe_event][3]接收Stripe事件,请使用gem 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 时,我会执行以下操作:

team.plan = team_plan
team.save!

我没有发现任何我能看到的错误,但该计划似乎没有得到更新。我也尝试过:

team_plan

但这给了我同样的结果。当我登录时,我已确认{{1}}是正确的计划,并且不是零。

关于我做错的任何想法?

1 个答案:

答案 0 :(得分:1)

尝试添加反向关系:

#Plan
has_many :teams, inverse_of: :plan

#Team
belongs_to :plan, inverse_of: teams

反向关系有助于确保在保存子对象时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}"

如果您对Rails记录器或pry或调试器感到满意,请使用它们而不是print语句。 :)

相关问题