【问题标题】:Sort records according to value in associated model根据关联模型中的值对记录进行排序
【发布时间】:2018-03-25 22:06:46
【问题描述】:

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

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

【问题讨论】:

    标签: mysql ruby-on-rails postgresql activerecord


    【解决方案1】:
    School
     .joins(:address)
     .select('schools.*, count(*) OVER (PARTITION BY addresses.city) AS count')
     .order('count DESC')
    

    【讨论】:

    • 不幸的是不能在 Postgresql 上工作。在分组子句中需要schools.id。我添加了这个,但是查询结果是错误的。
    • 更新了答案。 @user2942937
    猜你喜欢
    • 1970-01-01
    • 2020-04-16
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多