views:

265

answers:

1

Hi all. Rails newbie here. I'm trying to get some class methods into named_scopes. My application structure is similar to a blog application with user comments. Each comment model has a score attribute determined by ratings made from other users. I want to be able to have a named scope that returns the top ten users with the largest total scores from the sum of all the scores of each comment they have made.

To get the total score I've created this method:

class User < ActiveRecord::Base

#total score for all comments made by a particular user

  def total_score
comments.sum(:score)
  end

end

Then to get the top ten scores as a class method I use this:

class User < ActiveRecord::Base

#The top ten users ranked by total score

 def self.top_commenters
find(:all, :limit => 10).sort_by {|commenter| commenter.total_score}.reverse 
 end

end

I've been trying to get the same functionality into a named scope but I can't seem to figure it out.

Any suggestions?

+1  A: 
named_scope :top_commenters, :limit => 10, :order => "total_score DESC"
Ryan Bigg