【问题标题】:Could Not Find Inverse Association for has_many in Rails 3在 Rails 3 中找不到 has_many 的反向关联
【发布时间】:2013-06-21 10:54:06
【问题描述】:

我有以下型号:

class Business < ActiveRecord::Base
  has_many :customers, :inverse_of => :business
  has_many :payments, :inverse_of => :business
end

class Customer < ActiveRecord::Base
  belongs_to :business, :inverse_of => :customer
  has_many :payments, :inverse_of => :customer 
end

class Payment < ActiveRecord::Base
  belongs_to :customer, :inverse_of => :payment 
  belongs_to :business, :inverse_of => :payment
end

business.customers 工作正常。但是,当我执行business.payments 时,会出现错误:Could not find the inverse association for business (:payment in Business)

我不知道为什么。两种方式我都有相同的确切关联。我的 schema.db 看起来也不错。这可能是什么问题?

编辑 当我删除has_many :paymentsinverse_of =&gt; :business 时,它可以工作。为什么会这样?是否与付款属于客户和企业有关(这应该不重要,对吧?)?

【问题讨论】:

  • 您是否应用了正确的 rake 命令来更新数据库中的关联?
  • @wandarkaf 是的,db:migrate。当我第一次迁移时,这些关联就在那里。请参阅上面的编辑。

标签: ruby-on-rails ruby ruby-on-rails-3 associations


【解决方案1】:

使用此更新付款模式:

class Payment < ActiveRecord::Base
  belongs_to :customer, :inverse_of => :payments 
  belongs_to :business, :inverse_of => :payments
end

你声明了

has_many :payments, :inverse_of =&gt; :business 在商业模式中

但是在支付中你使用了belongs_to :business, :inverse_of =&gt; :payment

应该是belongs_to :business, :inverse_of =&gt; :payments

【讨论】:

  • 重点是你必须对 inverse_of: 参数使用正确的复数形式。如果它与许多付款相反,请使用 :payments,而不是 :payment。类似的业务
【解决方案2】:

您的问题出在:

belongs_to :business, :inverse_of => :customer

在:

belongs_to :customer, :inverse_of => :payment 
belongs_to :business, :inverse_of => :payment

belongs_to 的另一边是has_many,它定义了复数关系。这意味着inverse_of 应该是customers 而不是customerpayments 而不是payment

【讨论】:

    猜你喜欢
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多