2013-06-21 29 views
8

我有以下型號:找不到逆協會的has_many對Rails 3

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也很好看。這裏可能是什麼問題?

編輯 當我刪除了inverse_of => :businesshas_many :payments,它的工作原理。爲什麼會發生?這與支付是否屬於客戶和業務有關(它應該不重要,對嗎?)?

+0

沒有你應用正確的rake命令用於更新數據庫中的關聯? – wandarkaf

+0

@wandarkaf是的,db:migrate。這些協會從我第一次遷移時就在那裏。請參閱上面的編輯。 – darksky

回答

15

更新付款模式與此:

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

你的商業模式

但在付款時使用belongs_to :business, :inverse_of => :payment

宣佈

has_many :payments, :inverse_of => :business應該belongs_to :business, :inverse_of => :payments

+0

客戶爲什麼工作? – darksky

+0

重點是您必須對inverse_of:arguments使用適當的複數形式。如果它與許多付款相反,請使用:付款,而不是:付款。類似的業務 – Anwar

0

您的問題是在:

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