如何根据Rails中的连接表对结果进行排序? [英] How to sort results based on join table in Rails?
本文介绍了如何根据Rails中的连接表对结果进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有帐户模型,
class Account < ActiveRecord::Base
has_many :account_games
def score
account_games.map(&:score).sum
end
end
和帐户游戏:
class AccountGame < ActiveRecord::Base
belongs_to :account
end
获得最高分帐户的最佳方式是什么?如您所见, score 是相关 account_games score 字段的总和.
What is the best way to get accounts with the highest score? as you can see, score is the summation of related account_games score field.
谢谢
推荐答案
try
Account.joins(:account_games).sum('account_games.score', group: :account_id, order: 'sum_account_games_score')
这会给你一个哈希,其中键是 account_ids,值是总分.
which will give you a hash where the keys are the account_ids and the values are the total score.
您可以向帐户传递限制选项以获取前 x 个帐户.类似的东西
You can pass a limit option to accounts to get the top x accounts. something like
Account.limit(10).joins(:account_games).sum('account_games.score', group: :account_id, order: 'sum_account_games_score DESC')
这篇关于如何根据Rails中的连接表对结果进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文