【问题标题】:Mongoid: has_many relation with aliasMongoid:has_many 与别名的关系
【发布时间】:2013-03-12 02:05:04
【问题描述】:
背景:我有一个团队模型,它有_many 玩家,允许一个人打电话
@team.players
然后收到一个 Mongoid::Relations::Targets::Enumerable 玩家列表。
目标:我还希望能够检索球队中特定位置的球员名单。例如,如果用户在他的团队中添加了一个投手,我就可以调用
@team.pitchers 返回一个可枚举的投手列表。关于如何设置的任何想法?
【问题讨论】:
标签:
ruby-on-rails
ruby-on-rails-3
mongodb
mongoid
【解决方案1】:
不能在 mongoid 中的 has_many 中添加条件。
我能想到的两种方法是在玩家中设置范围并使用@team.players.pitchers 调用
Class Player
scope :pitchers, where(:position => "pitcher")
end
或者在团队中定义一个方法
Class Team
def pitchers
self.players.where(:position => "pitcher")
end
end