【问题标题】:rails convert class methods to named scoperails 将类方法转换为命名范围
【发布时间】:2009-11-06 01:38:44
【问题描述】:

Rails 新手在这里。我正在尝试将一些类方法放入 named_scopes。我的应用程序结构类似于带有用户 cmets 的博客应用程序。每个评论模型都有一个分数属性,该属性由其他用户的评分决定。我希望能够有一个命名范围,从他们所做的每条评论的所有分数的总和中返回总分最高的前十名用户。

为了获得总分我创建了这个方法:

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

我一直在尝试将相同的功能放入一个命名范围,但我似乎无法弄清楚。

有什么建议吗?

【问题讨论】:

标签: ruby-on-rails named-scope


【解决方案1】:
named_scope :top_commenters, :limit => 10, :order => "total_score DESC"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 2014-11-20
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多