所以我有以下内容......
我想要的是具有相关提供者数量的大学列表 但提供者也需要一个地址。
我尝试过:
@universities = University.joins(:providers).select('universities.id, universities.name, universities.slug, providers.id, count(providers.id) as count').group('universities.id').order('count').reverse
提供如下列表:
- id: 14
name: Salus University
slug: salus-university
count: 72
- id: 22
name: University of Florida
slug: university-of-florida
count: 45
问题是计数包括没有地址的提供商。所以我尝试了以下内容:
@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
但是,这给了我地址总数而不是地址提供者的数量:
- id: 14
name: Salus University
slug: salus-university
count: 90
- id: 22
name: University of Florida
slug: university-of-florida
count: 60
答案 0 :(得分:0)
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')