user1181031
user1181031

Reputation: 71

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

I have the following class:

class Team
  ...
  has_many :players
end

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

I want to create a scope :girl_team in class Team 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.

Upvotes: 0

Views: 155

Answers (1)

Ryan K
Ryan K

Reputation: 4053

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)

Upvotes: 1

Related Questions