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

前端 未结 7 2011
名媛妹妹
名媛妹妹 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:53

    I'd add this as a comment on the top answer, but I can't for some reason. According to this post:

    http://m.onkey.org/active-record-query-interface

    The User.all(options) method will be deprecated after Rails 3.0.3, and replaced with a bunch of other (handy, chainable) active record type stuff, but it makes it very hard to figure out how to put together the same kind of query.

    As a result, I've gone ahead and implemented the counter cache method. This was pretty easy and painless with the exception that you need to remember to update the column information in your migration, otherwise all existing records will have "0."

    Here's what I used in my migration:

    class AddUserCountToCollections < ActiveRecord::Migration
      def self.up
        add_column :collections, :collectionusers_count, :integer, :default => 0
        Collection.reset_column_information
        Collection.all.each do |c| 
          Collection.update_counters c.id, :collectionusers_count => c.collectionusers.count
        end
      end
    
      def self.down
        remove_column :collections, :collectionusers_count
      end
    end
    

    In theory this should be faster, too. Hope that's helpful going forward.

提交回复
热议问题