在多个表的rails上连接ruby中的操作

时间:2014-06-12 09:27:08

标签: ruby-on-rails postgresql

我的postgresql数据库中有三个表名为"审核","位置","公司"。

我想要通过连接这些表来检索数据。我有一个可执行的sql查询,它提供了我期望的结果。我想将它转换为ruby on rails。

select a.name as cname, b.name as lname, count(c.company_id) as count
from companies as a, locations as b, audits as c
where a.id=c.company_id and b.id =c.location_id
group by a.name,b.name;

1 个答案:

答案 0 :(得分:1)

我会尝试从您的查询中重新创建模型(我可能会弄错,所以您应该在查询中粘贴它):

class Company
  has_many :locations
  has_many :audits
end

class Location
  belongs_to :company
  has_many   :audits
end

class Audit
  belongs_to :company
  belongs_to :location
end

所以重新创建你的查询:

Company.joins(:locations, :audits)
  .group("companies.name", "locations.name")
  .count("audits.company_id")

结果将是一个散列,其中键是由company_name和location_name组成的数组,值是这样的计数:

{[company_name, location_name] => count, ...}

这将导致以下查询:

SELECT COUNT(audits.company_id) AS count_audits_company_id, companies.name AS companies_name, locations.name AS locations_name 
FROM "companies" INNER JOIN "locations" ON "locations"."company_id" = "companies"."id"
INNER JOIN "audits" ON "audits"."company_id" = "companies"."id" 
GROUP BY companies.name, locations.name

更多信息count