Rails effective SQL for "popular" users

I am creating a blog-type site in Rails (3), where β€œAuthors” can follow other authors and in order, and to find authors with most followers, I wrote this area:

scope :popular, all.sort { |a, b| a.followers.count <=> b.followers.count }

I know that this is really inefficient, since it has to execute several queries for each author in the database, and then compares the result. I ask this question to see if there is a better way to do this. The corresponding code is as follows:

class Author < ActiveRecord::Base

  has_many :relationships, :dependent => :destroy, :foreign_key => "follower_id"
  has_many :following, :through => :relationships, :source => :followed
  has_many :reverse_relationships, :dependent  => :destroy, :foreign_key => "followed_id",  :class_name => "Relationship"
  has_many :followers, :through => :reverse_relationships,  :source => :follower

  scope :popular, all.sort { |a, b| a.followers.count <=> b.followers.count }

end

"Followers" are implemented through a separate model:

class Relationship < ActiveRecord::Base

  belongs_to :follower, :class_name => "Author"
  belongs_to :followed, :class_name => "Author"

end

And to search for popular authors:

@popular_authors = Author.popular[0..9]

I would like to write something like Author.popular.limit(10), but I understand that in order for this to work, Author.popular must return a class object ActiveRecord::Relation, not an array.

, , , , 10 . !

+3
1

. , , , SELECT * from WHERE follower_id = 7

. , , 5000 .

SQL, GROUP_BY LIMIT = 10. 10 .

-

Authors.find(:all, :include => Authors, :group_by => " SELECT `count` as (some subquery I don't know to get the number of followers)", :limit => 10)

" "

+2

Source: https://habr.com/ru/post/1782014/


All Articles