2013-02-21 38 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

相關問題