Rails 3中has_many关联缺少反向关联

15

我有以下模型:

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 的时候出现了一个错误:在 Business 中找不到 payment 的反向关联

我不确定为什么会出现这种情况。我两种方式都用了完全相同的关联,我的 schema.db 也看起来很好。这里可能有什么问题呢?

编辑 当我删除 has_many :payments 中的 inverse_of => :business 后,它就可以工作了。为什么会这样呢?这与 Payment 属于 customer 和 business 有关吗(这实际上并不重要,对吗)?


你是否使用了正确的rake命令更新数据库中的关联? - wandarkaf
@wandarkaf 是的,db:migrate。关联是在我进行第一次迁移时创建的。请参见上面的编辑。 - darksky
2个回答

29

使用以下内容更新付款模型:

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

你在 Business 模型中声明了 has_many :payments, :inverse_of => :business

但是在 Payment 模型中你使用了 belongs_to :business, :inverse_of => :payment

应该改为 belongs_to :business, :inverse_of => :payments


1
重点是您必须为inverse_of参数使用正确的复数形式。如果它是许多付款的反向关系,请使用:payments而不是:payment。类似于business。 - Anwar

0

您的问题出在:

belongs_to :business, :inverse_of => :customer

并在:

belongs_to :customer, :inverse_of => :payment 
belongs_to :business, :inverse_of => :payment
< p > belongs_to 的另一面是 has_many,它定义了一个复数关系。这意味着 inverse_of 应该是 customers 而不是 customer,以及 payments 而不是 payment


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接