2009-11-06 31 views
0

Rails新手在這裏。我試圖讓一些類方法進入named_scopes。我的應用程序結構類似於具有用戶評論的博客應用程序。每個評論模型都有一個評分屬性,由其他用戶的評分確定。我希望能夠擁有一個命名範圍,該範圍從每個評論所有評分總和中返回總分最高的前十名用戶。rails將類方法轉換爲命名範圍

爲了讓我創造了這個方法的總比分:

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 

我一直在努力以獲得相同的功能到一個命名的範圍,但我似乎無法弄清楚。

有什麼建議嗎?

+0

哎呀,看起來像這個鏈接解釋了這一切:http://railsforum.com/viewtopic.php?id=28709 – 2009-11-06 02:00:48

回答

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