根据关联模型中的值对记录进行排序

时间:2017-10-13 17:54:37

标签: mysql ruby-on-rails postgresql activerecord

我有两种模式:学校和地址。

Address
    has_many :schools

School
    belongs_to :address

    t.bigint "address_id"

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

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(:地址).group(" schools.id,addresses.city")。order(" addresses.city ASC")但这只是允许按城市分组记录并忽略出现。

1 个答案:

答案 0 :(得分:1)

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