class User < ActiveRecord::Base
has_many :articles
end
class Article < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :articles
scope :by_articles_count, joins(:articles).group("users.id").order("count(articles.id) DESC")
end
...
User.by_articles_count
class User < ActiveRecord::Base
has_many :articles
scope :by_articles_count, includes(:articles).group("users.id").order("count(articles.id) DESC")
end
...
User.by_articles_count
stackoverflow-order-by-count-on-association stackoverflow-order-by-count-on-association2 有个现成的 gem: left_join
Preload, Eagerload, Includes and Joins
有理解不对的地方,希望大家不吝指正~