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工程:)
答
您可以使用有很多通过这个和钢轨是足够聪明的工作。
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)
我一直探索包括之前。但即使通过::客户端,我只能获取公司数据,而不是属性。 – gtheys 2014-12-05 09:57:10
也使用.select,似乎没有得到结果...也许我做错了。 – gtheys 2014-12-05 10:04:35
你不应该需要has_many通过加载。 – 2014-12-05 13:19:56