Rails 将类方法转换为命名范围
这里是 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
我一直在尝试将相同的功能放入命名范围中,但我似乎无法弄清楚它出去。
有什么建议吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)