2014-12-05 53 views
0

型號:activemodel的向上遍歷樹

Companies(has_many) -> (belongs_to)Clients(has_many) -> (belongs_to)Properties 

獲取列表下去是很容易做到:

company.clients -> shows all clients for that company 
client.properties -> show all properties for that client 

我想要做的是顯示出所有屬性(路線:properties_path ),但只適用於1家公司,並在視圖中提供客戶鏈接。

我有幾個解決方案:

  • 寫在SQL右外連接(使用的SQLite在我的開發ENV所以需要postgress得到它的工作)
    • 蠻力循環:讓所有的客戶那家公司,然後在1個散列

SO 3 M取每個客戶端的所有屬性Ÿ問題是有沒有更優雅的軌道方式來做到這一點,我錯過了?

我已探索包括。但是,這是我的問題:

[4] pry(main)> @company = Company.includes(clients: [:properties]).find(1)                          
    Company Load (0.2ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = ? LIMIT 1 [["id", 1]]                 
    Client Load (3.5ms) SELECT "clients".* FROM "clients" WHERE "clients"."company_id" IN (1)                      
    Property Load (5.9ms) SELECT "properties".* FROM "properties" WHERE "properties"."client_id" IN (2, 12)                  
=> #<Company id: 1, name: "coolDEVOPS2", created_at: "2014-10-31 11:05:05", updated_at: "2014-11-25 09:27:38">                 
[5] pry(main)> 

我沒有得到的屬性回來?

解決:我傻它的存在IRB /撬只打印第一記錄:)

@ company.properties工程:)

回答

0

您可以使用有很多通過這個和鋼軌是足夠聰明的工作。

class Company 
    has_many :clients 
    has_many :properties, through: :clients 
end 

class Client 
    belongs_to :company 
    has_many :properties 
end 

class Property 
    belongs_to :client 
end 

@company = Company.find(1) 
@company.properties 

但考慮到你想要的鏈接,客戶端太我猜你要循環客戶爲每個客戶端顯示的屬性,所以要預先加載

Company.includes(clients: [:properties]).find(1) 
+0

我一直探索包括之前。但即使通過::客戶端,我只能獲取公司數據,而不是屬性。 – gtheys 2014-12-05 09:57:10

+0

也使用.select,似乎沒有得到結果...也許我做錯了。 – gtheys 2014-12-05 10:04:35

+0

你不應該需要has_many通過加載。 – 2014-12-05 13:19:56