我有两个模型:学校和地址。

Address
    has_many :schools

School
    belongs_to :address

    t.bigint "address_id"


现在,我需要在School模型中建立范围,以根据地址表中城市的出现情况对学校进行排序。所以我需要以下结果:

School_1 | City_most_popular
School_2 | City_most_popular
School_3 | City_most_popular
School_4 | City_most_popular
School_5 | City_quite_popular
School_6 | City_quite_popular
School_7 | City_not_popular


我是这样写的:School.joins(:address).group(“ schools.id,addresss.city”)。order(“ addresses.city ASC”),但这仅允许按城市对记录进行分组,而忽略发生。

最佳答案

School
 .joins(:address)
 .select('schools.*, count(*) OVER (PARTITION BY addresses.city) AS count')
 .order('count DESC')

10-08 19:45