简体   繁体   English

Rails加入协会和计数

[英]Rails Join With Association and Count

So I have the following... 所以我有以下...

  • University - has many providers 大学 -有很多提供者
  • Provider - belongs to university, and has many addresses through positions 提供商 -属于大学,通过职位有很多地址
  • Position - belongs to provider and address 职位 -属于提供者和地址
  • Address - has many providers through positions 地址 -通过职位有很多提供商

What I want is a list of universities with associated provider count but the providers also need an address. 我想要的是列出具有相关提供者数量的大学,但提供者还需要一个地址。

What I have tried: 我尝试过的

@universities = University.joins(:providers).select('universities.id, universities.name, universities.slug, providers.id, count(providers.id) as count').group('universities.id').order('count').reverse

Provides a list like: 提供如下列表:

- id: 14
  name: Salus University
  slug: salus-university
  count: 72
- id: 22
  name: University of Florida
  slug: university-of-florida
  count: 45

The problem is the count includes providers with no address. 问题是计数包括没有地址的提供程序。 So I tried the following: 所以我尝试了以下方法:

@universities = University.joins(providers: :addresses).select('universities.id, universities.name, universities.slug, providers.id, count(providers.id) as count').group('universities.id').order('count').reverse

However, this gives me the count of the total number of addresses instead of providers with addresses: 但是,这给了我地址总数的计数,而不是地址提供者的计数:

- id: 14
  name: Salus University
  slug: salus-university
  count: 90
- id: 22
  name: University of Florida
  slug: university-of-florida
  count: 60

OK, I managed to figure this out finally. 好的,我终于弄清楚了。 I just joined with positions and added distinct to the count: 我只是加入了职位,并增加了distinct的数量:

@universities = University.joins(providers: :positions).select('universities.id, universities.name, universities.slug, providers.id, count(distinct providers.id) as count').group('universities.id').order('count desc')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM