向 select 最多用户持有的代币写入 ActiveRecord/AREL 查询

Writing an ActiveRecord/AREL query to select the coin held by the greatest numbers of users

简单说明一下:我有以下模型和关联:

User      has_many   :portfolios
          has many   :positions, through: portfolios
Portfolio has_many   :positions
Position  belongs_to :coin
Coin      has_many   :positions

我想 select 拥有最多用户的代币,但在想出正确的查询时有点费力。我可以想象写出类似 'find the coin that has the most positions, where the user_ids of the positions are distinct' 的内容。这是正确的想法吗?如何输入?

编辑:

def number_of_users
  count = 0
  User.all.each do |user|
    if user.positions.any?{|pos| pos.coin_id == self.id}
      count += 1
    end
  end
  return count
end

def self.with_most_holders
  self.all.max_by {|coin| coin.number_of_users}
end

有一种方法可以实现你想要的:

Coin
  .joins(positions: { portfolio: :user })
  .group("coins.id")
  .order("COUNT(DISTINCT(users.id)) DESC")
  .first