Rails 新手在这里。我正在尝试将一些类方法放入 named_scopes。我的应用程序结构类似于带有用户评论的博客应用程序。每个评论模型都有一个分数属性,该属性由其他用户的评分决定。我希望能够有一个命名范围,从他们所做的每条评论的所有分数的总和中返回总分最高的前十名用户。
为了获得总分,我创建了这个方法:
class User < ActiveRecord::Base
# total score for all comments made by a particular user
def total_score
comments.sum(:score)
end
end
然后为了获得前十名的分数作为一个类方法,我使用这个:
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
我一直在尝试将相同的功能放入命名范围,但我似乎无法弄清楚。
有什么建议么?