次のように2つのモデルをセットアップしています。
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
Railsコンソールで次のようなことをします:
@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])
ここで、params={:teacher_id=>1, :plan_id=>1, :email="example@example.com"}. ここでは、id が 1 のプランと教師が存在すると想定できます。
今、@stripe_subscription.stripe_plan.nil? true と評価されます。 しかし、そうすべきではありません。「サブスクリプション」と呼ばれるモデルと「プラン」と呼ばれるモデルが同じセットアップであった場合、@subscription.plan.nil? false と評価されます。これは不可解で、私はそれを理解しようと数時間費やしました. バグを見つけましたか、それとも何が間違っていますか? おそらく問題の一部は、:foreign_key が :stripe_plan_id ではなく :plan_id であることですか? has_many で :foreign_key 属性を設定するまで、別のバグが発生していました。