【问题标题】:Mongoid scope: how to check if an element is in collectionMongoid 范围:如何检查元素是否在集合中
【发布时间】:2023-03-12 08:29:01
【问题描述】:

我有以下课程:

class Team
  ...
  has_many :players
end

class Player
  ...
  field :gender, type: String
  belongs_to :Team
end

我想在 Team 类中创建一个 scope :girl_team,以便返回所有至少有 1 名球员性别为“女孩”的球队。

我不知道该怎么做。 我试过了:

scope :girl_team, ->{Where('player.gender' => "girl")}  

它似乎不起作用。

【问题讨论】:

    标签: ruby-on-rails ruby mongodb mongoid


    【解决方案1】:

    这需要JOIN。但是,MongoDB/Mongoid 中没有JOINs(与SQL/ActiveRecord 不同)。但是,如果您在 Teamembed Player(这是 MongoDB/Mongoid 独有/特殊的),那么 scope 将是:

    scope :girl_team, ->{where('players.gender' => "girl")}
    

    另一种解决方案是使用两个查询来获得你想要的:

    team_ids = Player.where(gender: "girl").distinct(:team_id)
    teams = Team.any_in(id: team_ids)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-05
      • 2010-11-23
      • 2021-12-22
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 2014-12-05
      • 2016-10-19
      相关资源
      最近更新 更多