我的目标是避免多次数据库查询并一次性完成所有操作
我有一个名为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
吗?
答案 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
就像一个不适合这种情况的过滤器。