2013-02-21 69 views
2

我的账户模型,如何根据Rails中的连接表对结果进行排序?

class Account < ActiveRecord::Base 
    has_many :account_games 
    def score 
    account_games.map(&:score).sum 
    end 
end 

而且AccountGame:

class AccountGame < ActiveRecord::Base 
    belongs_to :account 
end 

什么是获得最高得分帐户的最佳方式?正如你所看到的,分数是相关account_games分数字段的总和。

感谢

回答

1

尝试

Account.joins(:account_games).sum('account_games.score', group: :account_id, order: 'sum_account_games_score') 

,这将给你一个散列结果,其中的关键是account_ids和值的总得分。

您可以通过限制选项账户,以获得前X账户。像

Account.limit(10).joins(:account_games).sum('account_games.score', group: :account_id, order: 'sum_account_games_score DESC') 
+0

我以为我试图做的密切的事情,但我甚至没有关闭:)反正这给了我像=> {125 =># 115 =># 126 =># 116 =>#,117 =>#} – 2013-02-21 08:14:02

+0

毫米,但没有更多可读的方式来做到这一点,就像如果你想根据created_at,帐户中的天气或account_games进行更多查询? – 2013-02-21 08:17:11

+0

以及为什么我会收到BigDecimal而不是值? – 2013-02-21 08:19:17

相关问题