I have two models say: user and post
user.rb
has_many :posts
And post.rb
belongs_to :user, :index => true
I need to show users order_by number of posts added by them. One way to do this is: User.all.sort{|a,b| b.posts.count <=> a.posts.count}
But this is one of expensive operation.
Also I need a user with highest number of post. So having code like User.all.sort{|a,b| b.posts.count <=> a.posts.count}.first
is again another expensive operation.
Is there any other way to achieve this?
Aucun commentaire:
Enregistrer un commentaire