开发者

rails convert class methods to named scope

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 tota开发者_JAVA技巧l 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?


named_scope :top_commenters, :limit => 10, :order => "total_score DESC"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜