0

I have 2 models setup as follows:

class StripePlan < ActiveRecord::Base
  attr_accessible :location, :name, :price, :plan_type
  has_many :stripe_subscriptions, :foreign_key=>:plan_id
end

class StripeSubscription < ActiveRecord::Base
  attr_accessible :email, :plan_id, :stripe_customer_token, :teacher_id
  belongs_to :stripe_plan
  belongs_to :teacher
end

class Teacher < ActiveRecord::Base
   has_one :stripe_subscription, dependent: :destroy
end

I do something like the following at the rails console:

 @stripe_plan = StripePlan.find(params[:plan_id])
 @stripe_subscription = @stripe_plan.stripe_subscriptions.build(:teacher_id=>params[:teacher_id],:plan_id=>params[:plan_id],:email=>params[:email])

where params={:teacher_id=>1, :plan_id=>1, :email="example@example.com"}. Here you can assume a plan with id of 1 exists, as well as the teacher.

Now, @stripe_subscription.stripe_plan.nil? evaluates to true. But it shouldn't. Because if I had a model called "Subscription" and a model called "Plan" with the same setup, then @subscription.plan.nil? evaluates to false. This is puzzling and I've spent a couple of hours to try and figure it out. Have I found a bug or what am I doing wrong? Maybe part of the issue is the :foreign_key is :plan_id instead of :stripe_plan_id? I was getting another bug until I set the :foreign_key attribute in has_many.

4

2 回答 2

1

您必须@stripe_plan.save将项目保存到数据库。它仍然在记忆中。如果你做了 a@stripe_plan.stripe_subscriptions你仍然会看到它,因为它保存到 object @stripe_plan。直到你保存@string_plan它不会在数据库中。

你也可以做
@stripe_subscription = @stripe_plan.stripe_subscriptions.create(:teacher_id=>params[:teacher_id],:plan_id=>params[:plan_id],:email=>params[:email])

这将创建项目并保存到数据库

于 2012-11-27T19:25:03.273 回答
0

您不需要使用:plan_id=>params[:plan_id]in build,因为那会使用stripe_plan's id

你应该做的另一件事是看看 cosole。您可能错过了一些未列入白名单的属性。

查看Rails 3 -- Build not save to database (Railscast 196),您似乎遇到了类似的问题。

于 2012-09-22T03:26:01.183 回答