user1181031 user1181031 - 10 months ago 50
Ruby Question

Mongoid scope: how to check if an element is in collection

I have the following class:

class Team
has_many :players

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

I want to create a
scope :girl_team
in class
so that it will return all teams that has at least 1 player with "girl" as a gender.

I'm not sure how to do this.
I've tried:

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

it doesn't seem to work.


That would require a JOIN. However, there are no JOINs in MongoDB/Mongoid (unlike SQL/ActiveRecord). If, however, you embed Player in Team (which is unique/special to MongoDB/Mongoid), that scope would be:

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

Another solution is to use two queries to get what you want:

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