2017-05-30 116 views
0

我使用的鐵軌4.2.0 - 這是我的模型:ActiveRecord的:的has_many和包括

class Customer < ApplicationRecord 
    has_many :meters, -> { includes :contracts } 
end 

class Meter < ApplicationRecord 
    belongs_to :customer 
    has_many :contracts 
end 

class Contract < ApplicationRecord 
    belongs_to :meter 
end 

現在,我想顯示一個客戶的所有合約。按照Rails Guides我應該能夠做到這一點:

@customer.meters.contracts 

但是,這是行不通的。這是錯誤信息:

undefined method `contracts' for #<Meter::ActiveRecord_Associations_CollectionProxy:0x007fb0385730b0> 

在這種情況下最好的方法是什麼? 感謝您的幫助!

回答

0

與您的示例一樣,每個模型類僅代表數據庫記錄的這些實例之一,即Meter類僅表示meters表中的meter行。因此,考慮到這一點,您可以看到,聲明表示這些meter實例中的每一個都有很多contracts

我們把這個線下來:@customer.meters.contracts

你有你的@customer實例,你要求它爲所有的米:@customer.metersmeters方法的返回是屬於該@customermeters的集合。由於這是一個meter的實例,它有很多合同,所以你不能以這種方式要求收集米的合同。

你可以問它的個人計的,但:@customer.meters.first.contracts或者你可以遍歷所有的米,並得到所有的合同:

@customer.meters.flat_map(&:contracts) # => an array of all the contracts 

,或者更一般地說,你可能想顯示的列表客戶的合同中一個觀點:

<% @customer.meters.each do |meter| %> 
    <% meter.contracts.each do |contract| 
    // display the contract 
    <% end %> 
<% end %> 

但是,可以關聯所有contractscustomer通過meters協會:

class Customer < ApplicationRecord 
    has_many :meters, -> { includes :contracts } 
    # ActiveRecord's shorthand declaration for associating 
    # records through a join table, in this case 'meters' 
    has_many :contracts, through: :meters 
end 

通過添加has_many X, through: Y,您表示客戶記錄通過連接表Y與另一個表X中的記錄相關聯。

有了這個,給定一個customer與現有meters並具有現有contracts,你就可以調用這些@customer.contracts米,ActiveRecord的將客戶的meters他們contracts加盟取contracts並返回contracts集合。

更多關於Rails有很多通過關聯:http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

相關問題