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

前端 未结 7 2042
名媛妹妹
名媛妹妹 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 09:54

    The easiest way to achieve this is probably to add a counter cache to that model and then sort by that column.

    class Photo < ActiveRecord::Base
      belongs_to :user, :counter_cache => true
    end
    

    And be sure to add a column to your users table called photos_count.

    Then you will be able to...

    User.find(:all, :order => 'photos_count')
    

提交回复
热议问题