Rails 将类方法转换为命名范围

发布于 2024-08-11 01:14:03 字数 663 浏览 7 评论 0原文

这里是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

世界等同你 2024-08-18 01:14:03
named_scope :top_commenters, :limit => 10, :order => "total_score DESC"
named_scope :top_commenters, :limit => 10, :order => "total_score DESC"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文