Activemodel遍历树

时间:2014-12-05 09:39:45

标签: ruby-on-rails

型号:

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

我想要做的是显示所有属性(route:properties_path),但仅针对1家公司,并在视图中提供客户端的链接。

我有几个解决方案:

  • 在sql中编写右外连接(在我的开发环境中使用sqlite所以需要postgress才能使它工作)
    • 暴力循环:获取该公司的所有客户端,然后在每个客户端获取1个散列中的所有属性

所以我的问题是,有一种更优雅,也许有轨道方式可以做到这一点,我不知道了吗?

我已经探讨了包括。但这是我的问题:

[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 / pry打印第一条记录:)

  

@ company.properties有效:)

1 个答案:

答案 0 :(得分:0)

你可以使用很多功能,而rails足够聪明,可以解决这个问题。

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)
相关问题