【问题标题】:How to sort results based on join table in Rails?如何根据 Rails 中的连接表对结果进行排序?
【发布时间】:2013-02-21 08:04:30
【问题描述】:

我有帐户模型,

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

获得最高分帐户的最佳方法是什么?如您所见, score 是相关 account_games score 字段的总和。

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rails-activerecord


    【解决方案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')
    

    【讨论】:

    • 我以为我正在尝试做接近的事情,但我什至没有接近 :) 无论如何这给了我类似 => {125=>#<7ffdf1a67ba0><7ffdf1a67a88><7ffdf1a67740><7ffdf1a67290>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多