How to sort Rails AR.find by number of objects in a has_many relationship

前端 未结 7 2030
名媛妹妹
名媛妹妹 2020-12-24 09:32

How can I write an AR find query to have the results ordered by the number of records in a has_many association?

class User < ActiveRecord::Base
  has_man         


        
7条回答
  •  一个人的身影
    2020-12-24 10:01

    If you don't want an extra column, you could always ask for an extra column in the returned result set:

    User.all(:select => "#{User.table_name}.*, COUNT(#{Photo.table_name}.id) number_of_photos",
             :joins => :photos,
             :order => "number_of_photos")
    

    This generates the following SQL:

    SELECT users.*, COUNT(photos.id) number_of_photos
    FROM `users` INNER JOIN `photos` ON photos.user_id = users.id
    ORDER BY number_of_photos
    

提交回复
热议问题