【问题标题】:Why is this build association for has_many belongs_to not working in Rails 3.2.8?为什么这个 has_many belongs_to 的构建关联在 Rails 3.2.8 中不起作用?
【发布时间】:2012-09-22 03:00:24
【问题描述】:

我有 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”的模型具有相同的设置,那么@subscription.plan.nil?评估为假。这令人费解,我花了几个小时试图弄清楚。我是否发现了错误或我做错了什么?也许部分问题是 :foreign_key 是 :plan_id 而不是 :stripe_plan_id?在我在 has_many 中设置 :foreign_key 属性之前,我遇到了另一个错误。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord ruby-on-rails-3.2


    【解决方案1】:

    您必须执行@stripe_plan.save 才能将项目保存到数据库。它仍然在记忆中。如果您执行了@stripe_plan.stripe_subscriptions,您仍然会看到它,因为它已保存到对象@stripe_plan。在您保存 @string_plan 之前,它不会在数据库中。

    你也可以这样做
    @stripe_subscription = @stripe_plan.stripe_subscriptions.create(:teacher_id=&gt;params[:teacher_id],:plan_id=&gt;params[:plan_id],:email=&gt;params[:email])

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

    【讨论】:

      【解决方案2】:

      您不需要在build 中使用:plan_id=&gt;params[:plan_id],因为那样会使用stripe_planid

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

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

      【讨论】:

      • 感谢您在构建中不使用 :plan_id 是对的;在我的控制台上,从构建中创建了 StripeSubscription。没有质量分配错误。只是我似乎无法通过关联遍历@stripe_subscription.stripe_plan...我有相同的 has_many/belongs_to 设置与其他 2 个有效的模型,唯一不同的似乎是模型名称...这就是为什么这令人费解,让我有点发疯:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多