有没有办法从ruby mongoid查询返回has_many计算字段值?

时间:2017-04-21 00:23:55

标签: ruby mongoid

我的目标是避免多次数据库查询并一次性完成所有操作

我有一个名为Sponsor的文档对象模型,has_many players

class Sponsor
  include Mongoid::Document
  has_many :players
  field :name, type: String

  # . . .
end

class Player
  include Mongoid::Document
  belongs_to :sponsor, inverse_of: :players
  field :name, type: String
end

我想获得players我的Sponsor的数量,但我希望通过在Sponsor上调用类方法将其返回到我的返回赞助商对象中

class Sponsor
 # . . .

  def self.return_all_with_player_count
    # do something to get object with injected player count
  end

end

# Sponsor.return_all_with_player_count => [{name: 'Someone 1', player_count: 2}, {name: 'Someone 2', player_count: 12}]

##编辑

这会以某种方式使用scope吗?

1 个答案:

答案 0 :(得分:0)

尝试此实现,它将返回方法return_all_with_player_count所期望的内容。

  def self.return_all_with_player_count
    all.map do |sponsor|
      { name: sponsor.name, player_count: sponsor.players.count }
    end
  end

scope就像一个不适合这种情况的过滤器。