简体   繁体   中英

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:

@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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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