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 . !