def self.top_countries
joins(:recipes).
select('countries.id, count(*) AS recipes_count').
group('countries.id').
order('recipes_count DESC')
这会生成 SQL
select countries.id, count(*) AS recipes_count
from countries
join recipes on countries.id = recipes.country_id
group by countries.id
order by recipes_count
您会注意到 SELECT 中只有 2 列。
不是 Heroku 专家,我怀疑您可以通过明确列出您需要从国家/地区获得的所有列并按完整列列表分组来使其工作,即
def self.top_countries
joins(:recipes).
select('countries.id, countries.name, countries.other, count(*) AS recipes_count').
group('countries.id, countries.name, countries.other').
order('recipes_count DESC')
可能有一种更简洁的方法可以将原始答案(顶部)与另一个连接加入到top_countries
oncountries.id
以获取group by
.